1 /*
   2  * Copyright 1998-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_doCall.cpp.incl"
  27 
  28 #ifndef PRODUCT
  29 void trace_type_profile(ciMethod *method, int depth, int bci, ciMethod *prof_method, ciKlass *prof_klass, int site_count, int receiver_count) {
  30   if (TraceTypeProfile || PrintInlining || PrintOptoInlining) {
  31     tty->print("   ");
  32     for( int i = 0; i < depth; i++ ) tty->print("  ");
  33     if (!PrintOpto) {
  34       method->print_short_name();
  35       tty->print(" ->");
  36     }
  37     tty->print(" @ %d  ", bci);
  38     prof_method->print_short_name();
  39     tty->print("  >>TypeProfile (%d/%d counts) = ", receiver_count, site_count);
  40     prof_klass->name()->print_symbol();
  41     tty->print_cr(" (%d bytes)", prof_method->code_size());
  42   }
  43 }
  44 #endif
  45 
  46 CallGenerator* Compile::call_generator(ciMethod* call_method, int vtable_index, bool call_is_virtual, JVMState* jvms, bool allow_inline, float prof_factor) {
  47   CallGenerator* cg;
  48 
  49   // Dtrace currently doesn't work unless all calls are vanilla
  50   if (env()->dtrace_method_probes()) {
  51     allow_inline = false;
  52   }
  53 
  54   // Note: When we get profiling during stage-1 compiles, we want to pull
  55   // from more specific profile data which pertains to this inlining.
  56   // Right now, ignore the information in jvms->caller(), and do method[bci].
  57   ciCallProfile profile = jvms->method()->call_profile_at_bci(jvms->bci());
  58 
  59   // See how many times this site has been invoked.
  60   int site_count = profile.count();
  61   int receiver_count = -1;
  62   if (call_is_virtual && UseTypeProfile && profile.has_receiver(0)) {
  63     // Receivers in the profile structure are ordered by call counts
  64     // so that the most called (major) receiver is profile.receiver(0).
  65     receiver_count = profile.receiver_count(0);
  66   }
  67 
  68   CompileLog* log = this->log();
  69   if (log != NULL) {
  70     int rid = (receiver_count >= 0)? log->identify(profile.receiver(0)): -1;
  71     int r2id = (profile.morphism() == 2)? log->identify(profile.receiver(1)):-1;
  72     log->begin_elem("call method='%d' count='%d' prof_factor='%g'",
  73                     log->identify(call_method), site_count, prof_factor);
  74     if (call_is_virtual)  log->print(" virtual='1'");
  75     if (allow_inline)     log->print(" inline='1'");
  76     if (receiver_count >= 0) {
  77       log->print(" receiver='%d' receiver_count='%d'", rid, receiver_count);
  78       if (profile.has_receiver(1)) {
  79         log->print(" receiver2='%d' receiver2_count='%d'", r2id, profile.receiver_count(1));
  80       }
  81     }
  82     log->end_elem();
  83   }
  84 
  85   // Special case the handling of certain common, profitable library
  86   // methods.  If these methods are replaced with specialized code,
  87   // then we return it as the inlined version of the call.
  88   // We do this before the strict f.p. check below because the
  89   // intrinsics handle strict f.p. correctly.
  90   if (allow_inline) {
  91     cg = find_intrinsic(call_method, call_is_virtual);
  92     if (cg != NULL)  return cg;
  93   }
  94 
  95   // Do not inline strict fp into non-strict code, or the reverse
  96   bool caller_method_is_strict = jvms->method()->is_strict();
  97   if( caller_method_is_strict ^ call_method->is_strict() ) {
  98     allow_inline = false;
  99   }
 100 
 101   // Attempt to inline...
 102   if (allow_inline) {
 103     // The profile data is only partly attributable to this caller,
 104     // scale back the call site information.
 105     float past_uses = jvms->method()->scale_count(site_count, prof_factor);
 106     // This is the number of times we expect the call code to be used.
 107     float expected_uses = past_uses;
 108 
 109     // Try inlining a bytecoded method:
 110     if (!call_is_virtual) {
 111       InlineTree* ilt;
 112       if (UseOldInlining) {
 113         ilt = InlineTree::find_subtree_from_root(this->ilt(), jvms->caller(), jvms->method());
 114       } else {
 115         // Make a disembodied, stateless ILT.
 116         // TO DO:  When UseOldInlining is removed, copy the ILT code elsewhere.
 117         float site_invoke_ratio = prof_factor;
 118         // Note:  ilt is for the root of this parse, not the present call site.
 119         ilt = new InlineTree(this, jvms->method(), jvms->caller(), site_invoke_ratio);
 120       }
 121       WarmCallInfo scratch_ci;
 122       if (!UseOldInlining)
 123         scratch_ci.init(jvms, call_method, profile, prof_factor);
 124       WarmCallInfo* ci = ilt->ok_to_inline(call_method, jvms, profile, &scratch_ci);
 125       assert(ci != &scratch_ci, "do not let this pointer escape");
 126       bool allow_inline   = (ci != NULL && !ci->is_cold());
 127       bool require_inline = (allow_inline && ci->is_hot());
 128 
 129       if (allow_inline) {
 130         CallGenerator* cg = CallGenerator::for_inline(call_method, expected_uses);
 131         if (require_inline && cg != NULL && should_delay_inlining(call_method, jvms)) {
 132           // Delay the inlining of this method to give us the
 133           // opportunity to perform some high level optimizations
 134           // first.
 135           return CallGenerator::for_late_inline(call_method, cg);
 136         }
 137         if (cg == NULL) {
 138           // Fall through.
 139         } else if (require_inline || !InlineWarmCalls) {
 140           return cg;
 141         } else {
 142           CallGenerator* cold_cg = call_generator(call_method, vtable_index, call_is_virtual, jvms, false, prof_factor);
 143           return CallGenerator::for_warm_call(ci, cold_cg, cg);
 144         }
 145       }
 146     }
 147 
 148     // Try using the type profile.
 149     if (call_is_virtual && site_count > 0 && receiver_count > 0) {
 150       // The major receiver's count >= TypeProfileMajorReceiverPercent of site_count.
 151       bool have_major_receiver = (100.*profile.receiver_prob(0) >= (float)TypeProfileMajorReceiverPercent);
 152       ciMethod* receiver_method = NULL;
 153       if (have_major_receiver || profile.morphism() == 1 ||
 154           (profile.morphism() == 2 && UseBimorphicInlining)) {
 155         // receiver_method = profile.method();
 156         // Profiles do not suggest methods now.  Look it up in the major receiver.
 157         receiver_method = call_method->resolve_invoke(jvms->method()->holder(),
 158                                                       profile.receiver(0));
 159       }
 160       if (receiver_method != NULL) {
 161         // The single majority receiver sufficiently outweighs the minority.
 162         CallGenerator* hit_cg = this->call_generator(receiver_method,
 163               vtable_index, !call_is_virtual, jvms, allow_inline, prof_factor);
 164         if (hit_cg != NULL) {
 165           // Look up second receiver.
 166           CallGenerator* next_hit_cg = NULL;
 167           ciMethod* next_receiver_method = NULL;
 168           if (profile.morphism() == 2 && UseBimorphicInlining) {
 169             next_receiver_method = call_method->resolve_invoke(jvms->method()->holder(),
 170                                                                profile.receiver(1));
 171             if (next_receiver_method != NULL) {
 172               next_hit_cg = this->call_generator(next_receiver_method,
 173                                   vtable_index, !call_is_virtual, jvms,
 174                                   allow_inline, prof_factor);
 175               if (next_hit_cg != NULL && !next_hit_cg->is_inline() &&
 176                   have_major_receiver && UseOnlyInlinedBimorphic) {
 177                   // Skip if we can't inline second receiver's method
 178                   next_hit_cg = NULL;
 179               }
 180             }
 181           }
 182           CallGenerator* miss_cg;
 183           if (( profile.morphism() == 1 ||
 184                (profile.morphism() == 2 && next_hit_cg != NULL) ) &&
 185 
 186               !too_many_traps(Deoptimization::Reason_class_check)
 187 
 188               // Check only total number of traps per method to allow
 189               // the transition from monomorphic to bimorphic case between
 190               // compilations without falling into virtual call.
 191               // A monomorphic case may have the class_check trap flag is set
 192               // due to the time gap between the uncommon trap processing
 193               // when flags are set in MDO and the call site bytecode execution
 194               // in Interpreter when MDO counters are updated.
 195               // There was also class_check trap in monomorphic case due to
 196               // the bug 6225440.
 197 
 198              ) {
 199             // Generate uncommon trap for class check failure path
 200             // in case of monomorphic or bimorphic virtual call site.
 201             miss_cg = CallGenerator::for_uncommon_trap(call_method,
 202                         Deoptimization::Reason_class_check,
 203                         Deoptimization::Action_maybe_recompile);
 204           } else {
 205             // Generate virtual call for class check failure path
 206             // in case of polymorphic virtual call site.
 207             miss_cg = CallGenerator::for_virtual_call(call_method, vtable_index);
 208           }
 209           if (miss_cg != NULL) {
 210             if (next_hit_cg != NULL) {
 211               NOT_PRODUCT(trace_type_profile(jvms->method(), jvms->depth(), jvms->bci(), next_receiver_method, profile.receiver(1), site_count, profile.receiver_count(1)));
 212               // We don't need to record dependency on a receiver here and below.
 213               // Whenever we inline, the dependency is added by Parse::Parse().
 214               miss_cg = CallGenerator::for_predicted_call(profile.receiver(1), miss_cg, next_hit_cg, PROB_MAX);
 215             }
 216             if (miss_cg != NULL) {
 217               NOT_PRODUCT(trace_type_profile(jvms->method(), jvms->depth(), jvms->bci(), receiver_method, profile.receiver(0), site_count, receiver_count));
 218               cg = CallGenerator::for_predicted_call(profile.receiver(0), miss_cg, hit_cg, profile.receiver_prob(0));
 219               if (cg != NULL)  return cg;
 220             }
 221           }
 222         }
 223       }
 224     }
 225   }
 226 
 227   // There was no special inlining tactic, or it bailed out.
 228   // Use a more generic tactic, like a simple call.
 229   if (call_is_virtual) {
 230     return CallGenerator::for_virtual_call(call_method, vtable_index);
 231   } else {
 232     // Class Hierarchy Analysis or Type Profile reveals a unique target,
 233     // or it is a static or special call.
 234     return CallGenerator::for_direct_call(call_method, should_delay_inlining(call_method, jvms));
 235   }
 236 }
 237 
 238 // Return true for methods that shouldn't be inlined early so that
 239 // they are easier to analyze and optimize as intrinsics.
 240 bool Compile::should_delay_inlining(ciMethod* call_method, JVMState* jvms) {
 241   if (has_stringbuilder()) {
 242 
 243     if ((call_method->holder() == C->env()->StringBuilder_klass() ||
 244          call_method->holder() == C->env()->StringBuffer_klass()) &&
 245         (jvms->method()->holder() == C->env()->StringBuilder_klass() ||
 246          jvms->method()->holder() == C->env()->StringBuffer_klass())) {
 247       // Delay SB calls only when called from non-SB code
 248       return false;
 249     }
 250 
 251     switch (call_method->intrinsic_id()) {
 252       case vmIntrinsics::_StringBuilder_void:
 253       case vmIntrinsics::_StringBuilder_int:
 254       case vmIntrinsics::_StringBuilder_String:
 255       case vmIntrinsics::_StringBuilder_append_char:
 256       case vmIntrinsics::_StringBuilder_append_int:
 257       case vmIntrinsics::_StringBuilder_append_String:
 258       case vmIntrinsics::_StringBuilder_toString:
 259       case vmIntrinsics::_StringBuffer_void:
 260       case vmIntrinsics::_StringBuffer_int:
 261       case vmIntrinsics::_StringBuffer_String:
 262       case vmIntrinsics::_StringBuffer_append_char:
 263       case vmIntrinsics::_StringBuffer_append_int:
 264       case vmIntrinsics::_StringBuffer_append_String:
 265       case vmIntrinsics::_StringBuffer_toString:
 266       case vmIntrinsics::_Integer_toString:
 267         return true;
 268 
 269       case vmIntrinsics::_String_String:
 270         {
 271           Node* receiver = jvms->map()->in(jvms->argoff() + 1);
 272           if (receiver->is_Proj() && receiver->in(0)->is_CallStaticJava()) {
 273             CallStaticJavaNode* csj = receiver->in(0)->as_CallStaticJava();
 274             ciMethod* m = csj->method();
 275             if (m != NULL &&
 276                 (m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString ||
 277                  m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString))
 278               // Delay String.<init>(new SB())
 279               return true;
 280           }
 281           return false;
 282         }
 283 
 284       default:
 285         return false;
 286     }
 287   }
 288   return false;
 289 }
 290 
 291 
 292 // uncommon-trap call-sites where callee is unloaded, uninitialized or will not link
 293 bool Parse::can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass* klass) {
 294   // Additional inputs to consider...
 295   // bc      = bc()
 296   // caller  = method()
 297   // iter().get_method_holder_index()
 298   assert( dest_method->is_loaded(), "ciTypeFlow should not let us get here" );
 299   // Interface classes can be loaded & linked and never get around to
 300   // being initialized.  Uncommon-trap for not-initialized static or
 301   // v-calls.  Let interface calls happen.
 302   ciInstanceKlass* holder_klass  = dest_method->holder();
 303   if (!holder_klass->is_initialized() &&
 304       !holder_klass->is_interface()) {
 305     uncommon_trap(Deoptimization::Reason_uninitialized,
 306                   Deoptimization::Action_reinterpret,
 307                   holder_klass);
 308     return true;
 309   }
 310   if (dest_method->is_method_handle_invoke()
 311       && holder_klass->name() == ciSymbol::java_dyn_Dynamic()) {
 312     // FIXME: NYI
 313     uncommon_trap(Deoptimization::Reason_unhandled,
 314                   Deoptimization::Action_none,
 315                   holder_klass);
 316     return true;
 317   }
 318 
 319   assert(dest_method->will_link(method()->holder(), klass, bc()), "dest_method: typeflow responsibility");
 320   return false;
 321 }
 322 
 323 
 324 //------------------------------do_call----------------------------------------
 325 // Handle your basic call.  Inline if we can & want to, else just setup call.
 326 void Parse::do_call() {
 327   // It's likely we are going to add debug info soon.
 328   // Also, if we inline a guy who eventually needs debug info for this JVMS,
 329   // our contribution to it is cleaned up right here.
 330   kill_dead_locals();
 331 
 332   // Set frequently used booleans
 333   bool is_virtual = bc() == Bytecodes::_invokevirtual;
 334   bool is_virtual_or_interface = is_virtual || bc() == Bytecodes::_invokeinterface;
 335   bool has_receiver = is_virtual_or_interface || bc() == Bytecodes::_invokespecial;
 336 
 337   // Find target being called
 338   bool             will_link;
 339   ciMethod*        dest_method   = iter().get_method(will_link);
 340   ciInstanceKlass* holder_klass  = dest_method->holder();
 341   ciKlass* holder = iter().get_declared_method_holder();
 342   ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);
 343 
 344   int   nargs    = dest_method->arg_size();
 345 
 346   // uncommon-trap when callee is unloaded, uninitialized or will not link
 347   // bailout when too many arguments for register representation
 348   if (!will_link || can_not_compile_call_site(dest_method, klass)) {
 349 #ifndef PRODUCT
 350     if (PrintOpto && (Verbose || WizardMode)) {
 351       method()->print_name(); tty->print_cr(" can not compile call at bci %d to:", bci());
 352       dest_method->print_name(); tty->cr();
 353     }
 354 #endif
 355     return;
 356   }
 357   assert(holder_klass->is_loaded(), "");
 358   assert(dest_method->is_static() == !has_receiver, "must match bc");
 359   // Note: this takes into account invokeinterface of methods declared in java/lang/Object,
 360   // which should be invokevirtuals but according to the VM spec may be invokeinterfaces
 361   assert(holder_klass->is_interface() || holder_klass->super() == NULL || (bc() != Bytecodes::_invokeinterface), "must match bc");
 362   // Note:  In the absence of miranda methods, an abstract class K can perform
 363   // an invokevirtual directly on an interface method I.m if K implements I.
 364 
 365   // ---------------------
 366   // Does Class Hierarchy Analysis reveal only a single target of a v-call?
 367   // Then we may inline or make a static call, but become dependent on there being only 1 target.
 368   // Does the call-site type profile reveal only one receiver?
 369   // Then we may introduce a run-time check and inline on the path where it succeeds.
 370   // The other path may uncommon_trap, check for another receiver, or do a v-call.
 371 
 372   // Choose call strategy.
 373   bool call_is_virtual = is_virtual_or_interface;
 374   int vtable_index = methodOopDesc::invalid_vtable_index;
 375   ciMethod* call_method = dest_method;
 376 
 377   // Try to get the most accurate receiver type
 378   if (is_virtual_or_interface) {
 379     Node*             receiver_node = stack(sp() - nargs);
 380     const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();
 381     ciMethod* optimized_virtual_method = optimize_inlining(method(), bci(), klass, dest_method, receiver_type);
 382 
 383     // Have the call been sufficiently improved such that it is no longer a virtual?
 384     if (optimized_virtual_method != NULL) {
 385       call_method     = optimized_virtual_method;
 386       call_is_virtual = false;
 387     } else if (!UseInlineCaches && is_virtual && call_method->is_loaded()) {
 388       // We can make a vtable call at this site
 389       vtable_index = call_method->resolve_vtable_index(method()->holder(), klass);
 390     }
 391   }
 392 
 393   // Note:  It's OK to try to inline a virtual call.
 394   // The call generator will not attempt to inline a polymorphic call
 395   // unless it knows how to optimize the receiver dispatch.
 396   bool try_inline = (C->do_inlining() || InlineAccessors);
 397 
 398   // ---------------------
 399   inc_sp(- nargs);              // Temporarily pop args for JVM state of call
 400   JVMState* jvms = sync_jvms();
 401 
 402   // ---------------------
 403   // Decide call tactic.
 404   // This call checks with CHA, the interpreter profile, intrinsics table, etc.
 405   // It decides whether inlining is desirable or not.
 406   CallGenerator* cg = C->call_generator(call_method, vtable_index, call_is_virtual, jvms, try_inline, prof_factor());
 407 
 408   // ---------------------
 409   // Round double arguments before call
 410   round_double_arguments(dest_method);
 411 
 412 #ifndef PRODUCT
 413   // bump global counters for calls
 414   count_compiled_calls(false/*at_method_entry*/, cg->is_inline());
 415 
 416   // Record first part of parsing work for this call
 417   parse_histogram()->record_change();
 418 #endif // not PRODUCT
 419 
 420   assert(jvms == this->jvms(), "still operating on the right JVMS");
 421   assert(jvms_in_sync(),       "jvms must carry full info into CG");
 422 
 423   // save across call, for a subsequent cast_not_null.
 424   Node* receiver = has_receiver ? argument(0) : NULL;
 425 
 426   // Bump method data counters (We profile *before* the call is made
 427   // because exceptions don't return to the call site.)
 428   profile_call(receiver);
 429 
 430   JVMState* new_jvms;
 431   if ((new_jvms = cg->generate(jvms)) == NULL) {
 432     // When inlining attempt fails (e.g., too many arguments),
 433     // it may contaminate the current compile state, making it
 434     // impossible to pull back and try again.  Once we call
 435     // cg->generate(), we are committed.  If it fails, the whole
 436     // compilation task is compromised.
 437     if (failing())  return;
 438 #ifndef PRODUCT
 439     if (PrintOpto || PrintOptoInlining || PrintInlining) {
 440       // Only one fall-back, so if an intrinsic fails, ignore any bytecodes.
 441       if (cg->is_intrinsic() && call_method->code_size() > 0) {
 442         tty->print("Bailed out of intrinsic, will not inline: ");
 443         call_method->print_name(); tty->cr();
 444       }
 445     }
 446 #endif
 447     // This can happen if a library intrinsic is available, but refuses
 448     // the call site, perhaps because it did not match a pattern the
 449     // intrinsic was expecting to optimize.  The fallback position is
 450     // to call out-of-line.
 451     try_inline = false;  // Inline tactic bailed out.
 452     cg = C->call_generator(call_method, vtable_index, call_is_virtual, jvms, try_inline, prof_factor());
 453     if ((new_jvms = cg->generate(jvms)) == NULL) {
 454       guarantee(failing(), "call failed to generate:  calls should work");
 455       return;
 456     }
 457   }
 458 
 459   if (cg->is_inline()) {
 460     // Accumulate has_loops estimate
 461     C->set_has_loops(C->has_loops() || call_method->has_loops());
 462     C->env()->notice_inlined_method(call_method);
 463   }
 464 
 465   // Reset parser state from [new_]jvms, which now carries results of the call.
 466   // Return value (if any) is already pushed on the stack by the cg.
 467   add_exception_states_from(new_jvms);
 468   if (new_jvms->map()->control() == top()) {
 469     stop_and_kill_map();
 470   } else {
 471     assert(new_jvms->same_calls_as(jvms), "method/bci left unchanged");
 472     set_jvms(new_jvms);
 473   }
 474 
 475   if (!stopped()) {
 476     // This was some sort of virtual call, which did a null check for us.
 477     // Now we can assert receiver-not-null, on the normal return path.
 478     if (receiver != NULL && cg->is_virtual()) {
 479       Node* cast = cast_not_null(receiver);
 480       // %%% assert(receiver == cast, "should already have cast the receiver");
 481     }
 482 
 483     // Round double result after a call from strict to non-strict code
 484     round_double_result(dest_method);
 485 
 486     // If the return type of the method is not loaded, assert that the
 487     // value we got is a null.  Otherwise, we need to recompile.
 488     if (!dest_method->return_type()->is_loaded()) {
 489 #ifndef PRODUCT
 490       if (PrintOpto && (Verbose || WizardMode)) {
 491         method()->print_name(); tty->print_cr(" asserting nullness of result at bci: %d", bci());
 492         dest_method->print_name(); tty->cr();
 493       }
 494 #endif
 495       if (C->log() != NULL) {
 496         C->log()->elem("assert_null reason='return' klass='%d'",
 497                        C->log()->identify(dest_method->return_type()));
 498       }
 499       // If there is going to be a trap, put it at the next bytecode:
 500       set_bci(iter().next_bci());
 501       do_null_assert(peek(), T_OBJECT);
 502       set_bci(iter().cur_bci()); // put it back
 503     }
 504   }
 505 
 506   // Restart record of parsing work after possible inlining of call
 507 #ifndef PRODUCT
 508   parse_histogram()->set_initial_state(bc());
 509 #endif
 510 }
 511 
 512 //---------------------------catch_call_exceptions-----------------------------
 513 // Put a Catch and CatchProj nodes behind a just-created call.
 514 // Send their caught exceptions to the proper handler.
 515 // This may be used after a call to the rethrow VM stub,
 516 // when it is needed to process unloaded exception classes.
 517 void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) {
 518   // Exceptions are delivered through this channel:
 519   Node* i_o = this->i_o();
 520 
 521   // Add a CatchNode.
 522   GrowableArray<int>* bcis = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, -1);
 523   GrowableArray<const Type*>* extypes = new (C->node_arena()) GrowableArray<const Type*>(C->node_arena(), 8, 0, NULL);
 524   GrowableArray<int>* saw_unloaded = new (C->node_arena()) GrowableArray<int>(C->node_arena(), 8, 0, 0);
 525 
 526   for (; !handlers.is_done(); handlers.next()) {
 527     ciExceptionHandler* h        = handlers.handler();
 528     int                 h_bci    = h->handler_bci();
 529     ciInstanceKlass*    h_klass  = h->is_catch_all() ? env()->Throwable_klass() : h->catch_klass();
 530     // Do not introduce unloaded exception types into the graph:
 531     if (!h_klass->is_loaded()) {
 532       if (saw_unloaded->contains(h_bci)) {
 533         /* We've already seen an unloaded exception with h_bci,
 534            so don't duplicate. Duplication will cause the CatchNode to be
 535            unnecessarily large. See 4713716. */
 536         continue;
 537       } else {
 538         saw_unloaded->append(h_bci);
 539       }
 540     }
 541     const Type*         h_extype = TypeOopPtr::make_from_klass(h_klass);
 542     // (We use make_from_klass because it respects UseUniqueSubclasses.)
 543     h_extype = h_extype->join(TypeInstPtr::NOTNULL);
 544     assert(!h_extype->empty(), "sanity");
 545     // Note:  It's OK if the BCIs repeat themselves.
 546     bcis->append(h_bci);
 547     extypes->append(h_extype);
 548   }
 549 
 550   int len = bcis->length();
 551   CatchNode *cn = new (C, 2) CatchNode(control(), i_o, len+1);
 552   Node *catch_ = _gvn.transform(cn);
 553 
 554   // now branch with the exception state to each of the (potential)
 555   // handlers
 556   for(int i=0; i < len; i++) {
 557     // Setup JVM state to enter the handler.
 558     PreserveJVMState pjvms(this);
 559     // Locals are just copied from before the call.
 560     // Get control from the CatchNode.
 561     int handler_bci = bcis->at(i);
 562     Node* ctrl = _gvn.transform( new (C, 1) CatchProjNode(catch_, i+1,handler_bci));
 563     // This handler cannot happen?
 564     if (ctrl == top())  continue;
 565     set_control(ctrl);
 566 
 567     // Create exception oop
 568     const TypeInstPtr* extype = extypes->at(i)->is_instptr();
 569     Node *ex_oop = _gvn.transform(new (C, 2) CreateExNode(extypes->at(i), ctrl, i_o));
 570 
 571     // Handle unloaded exception classes.
 572     if (saw_unloaded->contains(handler_bci)) {
 573       // An unloaded exception type is coming here.  Do an uncommon trap.
 574 #ifndef PRODUCT
 575       // We do not expect the same handler bci to take both cold unloaded
 576       // and hot loaded exceptions.  But, watch for it.
 577       if (extype->is_loaded()) {
 578         tty->print_cr("Warning: Handler @%d takes mixed loaded/unloaded exceptions in ");
 579         method()->print_name(); tty->cr();
 580       } else if (PrintOpto && (Verbose || WizardMode)) {
 581         tty->print("Bailing out on unloaded exception type ");
 582         extype->klass()->print_name();
 583         tty->print(" at bci:%d in ", bci());
 584         method()->print_name(); tty->cr();
 585       }
 586 #endif
 587       // Emit an uncommon trap instead of processing the block.
 588       set_bci(handler_bci);
 589       push_ex_oop(ex_oop);
 590       uncommon_trap(Deoptimization::Reason_unloaded,
 591                     Deoptimization::Action_reinterpret,
 592                     extype->klass(), "!loaded exception");
 593       set_bci(iter().cur_bci()); // put it back
 594       continue;
 595     }
 596 
 597     // go to the exception handler
 598     if (handler_bci < 0) {     // merge with corresponding rethrow node
 599       throw_to_exit(make_exception_state(ex_oop));
 600     } else {                      // Else jump to corresponding handle
 601       push_ex_oop(ex_oop);        // Clear stack and push just the oop.
 602       merge_exception(handler_bci);
 603     }
 604   }
 605 
 606   // The first CatchProj is for the normal return.
 607   // (Note:  If this is a call to rethrow_Java, this node goes dead.)
 608   set_control(_gvn.transform( new (C, 1) CatchProjNode(catch_, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci)));
 609 }
 610 
 611 
 612 //----------------------------catch_inline_exceptions--------------------------
 613 // Handle all exceptions thrown by an inlined method or individual bytecode.
 614 // Common case 1: we have no handler, so all exceptions merge right into
 615 // the rethrow case.
 616 // Case 2: we have some handlers, with loaded exception klasses that have
 617 // no subklasses.  We do a Deutsch-Shiffman style type-check on the incoming
 618 // exception oop and branch to the handler directly.
 619 // Case 3: We have some handlers with subklasses or are not loaded at
 620 // compile-time.  We have to call the runtime to resolve the exception.
 621 // So we insert a RethrowCall and all the logic that goes with it.
 622 void Parse::catch_inline_exceptions(SafePointNode* ex_map) {
 623   // Caller is responsible for saving away the map for normal control flow!
 624   assert(stopped(), "call set_map(NULL) first");
 625   assert(method()->has_exception_handlers(), "don't come here w/o work to do");
 626 
 627   Node* ex_node = saved_ex_oop(ex_map);
 628   if (ex_node == top()) {
 629     // No action needed.
 630     return;
 631   }
 632   const TypeInstPtr* ex_type = _gvn.type(ex_node)->isa_instptr();
 633   NOT_PRODUCT(if (ex_type==NULL) tty->print_cr("*** Exception not InstPtr"));
 634   if (ex_type == NULL)
 635     ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr();
 636 
 637   // determine potential exception handlers
 638   ciExceptionHandlerStream handlers(method(), bci(),
 639                                     ex_type->klass()->as_instance_klass(),
 640                                     ex_type->klass_is_exact());
 641 
 642   // Start executing from the given throw state.  (Keep its stack, for now.)
 643   // Get the exception oop as known at compile time.
 644   ex_node = use_exception_state(ex_map);
 645 
 646   // Get the exception oop klass from its header
 647   Node* ex_klass_node = NULL;
 648   if (has_ex_handler() && !ex_type->klass_is_exact()) {
 649     Node* p = basic_plus_adr( ex_node, ex_node, oopDesc::klass_offset_in_bytes());
 650     ex_klass_node = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT) );
 651 
 652     // Compute the exception klass a little more cleverly.
 653     // Obvious solution is to simple do a LoadKlass from the 'ex_node'.
 654     // However, if the ex_node is a PhiNode, I'm going to do a LoadKlass for
 655     // each arm of the Phi.  If I know something clever about the exceptions
 656     // I'm loading the class from, I can replace the LoadKlass with the
 657     // klass constant for the exception oop.
 658     if( ex_node->is_Phi() ) {
 659       ex_klass_node = new (C, ex_node->req()) PhiNode( ex_node->in(0), TypeKlassPtr::OBJECT );
 660       for( uint i = 1; i < ex_node->req(); i++ ) {
 661         Node* p = basic_plus_adr( ex_node->in(i), ex_node->in(i), oopDesc::klass_offset_in_bytes() );
 662         Node* k = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT) );
 663         ex_klass_node->init_req( i, k );
 664       }
 665       _gvn.set_type(ex_klass_node, TypeKlassPtr::OBJECT);
 666 
 667     }
 668   }
 669 
 670   // Scan the exception table for applicable handlers.
 671   // If none, we can call rethrow() and be done!
 672   // If precise (loaded with no subklasses), insert a D.S. style
 673   // pointer compare to the correct handler and loop back.
 674   // If imprecise, switch to the Rethrow VM-call style handling.
 675 
 676   int remaining = handlers.count_remaining();
 677 
 678   // iterate through all entries sequentially
 679   for (;!handlers.is_done(); handlers.next()) {
 680     // Do nothing if turned off
 681     if( !DeutschShiffmanExceptions ) break;
 682     ciExceptionHandler* handler = handlers.handler();
 683 
 684     if (handler->is_rethrow()) {
 685       // If we fell off the end of the table without finding an imprecise
 686       // exception klass (and without finding a generic handler) then we
 687       // know this exception is not handled in this method.  We just rethrow
 688       // the exception into the caller.
 689       throw_to_exit(make_exception_state(ex_node));
 690       return;
 691     }
 692 
 693     // exception handler bci range covers throw_bci => investigate further
 694     int handler_bci = handler->handler_bci();
 695 
 696     if (remaining == 1) {
 697       push_ex_oop(ex_node);        // Push exception oop for handler
 698 #ifndef PRODUCT
 699       if (PrintOpto && WizardMode) {
 700         tty->print_cr("  Catching every inline exception bci:%d -> handler_bci:%d", bci(), handler_bci);
 701       }
 702 #endif
 703       merge_exception(handler_bci); // jump to handler
 704       return;                   // No more handling to be done here!
 705     }
 706 
 707     // %%% The following logic replicates make_from_klass_unique.
 708     // TO DO:  Replace by a subroutine call.  Then generalize
 709     // the type check, as noted in the next "%%%" comment.
 710 
 711     ciInstanceKlass* klass = handler->catch_klass();
 712     if (UseUniqueSubclasses) {
 713       // (We use make_from_klass because it respects UseUniqueSubclasses.)
 714       const TypeOopPtr* tp = TypeOopPtr::make_from_klass(klass);
 715       klass = tp->klass()->as_instance_klass();
 716     }
 717 
 718     // Get the handler's klass
 719     if (!klass->is_loaded())    // klass is not loaded?
 720       break;                    // Must call Rethrow!
 721     if (klass->is_interface())  // should not happen, but...
 722       break;                    // bail out
 723     // See if the loaded exception klass has no subtypes
 724     if (klass->has_subklass())
 725       break;                    // Cannot easily do precise test ==> Rethrow
 726 
 727     // %%% Now that subclass checking is very fast, we need to rewrite
 728     // this section and remove the option "DeutschShiffmanExceptions".
 729     // The exception processing chain should be a normal typecase pattern,
 730     // with a bailout to the interpreter only in the case of unloaded
 731     // classes.  (The bailout should mark the method non-entrant.)
 732     // This rewrite should be placed in GraphKit::, not Parse::.
 733 
 734     // Add a dependence; if any subclass added we need to recompile
 735     // %%% should use stronger assert_unique_concrete_subtype instead
 736     if (!klass->is_final()) {
 737       C->dependencies()->assert_leaf_type(klass);
 738     }
 739 
 740     // Implement precise test
 741     const TypeKlassPtr *tk = TypeKlassPtr::make(klass);
 742     Node* con = _gvn.makecon(tk);
 743     Node* cmp = _gvn.transform( new (C, 3) CmpPNode(ex_klass_node, con) );
 744     Node* bol = _gvn.transform( new (C, 2) BoolNode(cmp, BoolTest::ne) );
 745     { BuildCutout unless(this, bol, PROB_LIKELY(0.7f));
 746       const TypeInstPtr* tinst = TypeInstPtr::make_exact(TypePtr::NotNull, klass);
 747       Node* ex_oop = _gvn.transform(new (C, 2) CheckCastPPNode(control(), ex_node, tinst));
 748       push_ex_oop(ex_oop);      // Push exception oop for handler
 749 #ifndef PRODUCT
 750       if (PrintOpto && WizardMode) {
 751         tty->print("  Catching inline exception bci:%d -> handler_bci:%d -- ", bci(), handler_bci);
 752         klass->print_name();
 753         tty->cr();
 754       }
 755 #endif
 756       merge_exception(handler_bci);
 757     }
 758 
 759     // Come here if exception does not match handler.
 760     // Carry on with more handler checks.
 761     --remaining;
 762   }
 763 
 764   assert(!stopped(), "you should return if you finish the chain");
 765 
 766   if (remaining == 1) {
 767     // Further checks do not matter.
 768   }
 769 
 770   if (can_rerun_bytecode()) {
 771     // Do not push_ex_oop here!
 772     // Re-executing the bytecode will reproduce the throwing condition.
 773     bool must_throw = true;
 774     uncommon_trap(Deoptimization::Reason_unhandled,
 775                   Deoptimization::Action_none,
 776                   (ciKlass*)NULL, (const char*)NULL, // default args
 777                   must_throw);
 778     return;
 779   }
 780 
 781   // Oops, need to call into the VM to resolve the klasses at runtime.
 782   // Note:  This call must not deoptimize, since it is not a real at this bci!
 783   kill_dead_locals();
 784 
 785   make_runtime_call(RC_NO_LEAF | RC_MUST_THROW,
 786                     OptoRuntime::rethrow_Type(),
 787                     OptoRuntime::rethrow_stub(),
 788                     NULL, NULL,
 789                     ex_node);
 790 
 791   // Rethrow is a pure call, no side effects, only a result.
 792   // The result cannot be allocated, so we use I_O
 793 
 794   // Catch exceptions from the rethrow
 795   catch_call_exceptions(handlers);
 796 }
 797 
 798 
 799 // (Note:  Moved add_debug_info into GraphKit::add_safepoint_edges.)
 800 
 801 
 802 #ifndef PRODUCT
 803 void Parse::count_compiled_calls(bool at_method_entry, bool is_inline) {
 804   if( CountCompiledCalls ) {
 805     if( at_method_entry ) {
 806       // bump invocation counter if top method (for statistics)
 807       if (CountCompiledCalls && depth() == 1) {
 808         const TypeInstPtr* addr_type = TypeInstPtr::make(method());
 809         Node* adr1 = makecon(addr_type);
 810         Node* adr2 = basic_plus_adr(adr1, adr1, in_bytes(methodOopDesc::compiled_invocation_counter_offset()));
 811         increment_counter(adr2);
 812       }
 813     } else if (is_inline) {
 814       switch (bc()) {
 815       case Bytecodes::_invokevirtual:   increment_counter(SharedRuntime::nof_inlined_calls_addr()); break;
 816       case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_inlined_interface_calls_addr()); break;
 817       case Bytecodes::_invokestatic:
 818       case Bytecodes::_invokedynamic:
 819       case Bytecodes::_invokespecial:   increment_counter(SharedRuntime::nof_inlined_static_calls_addr()); break;
 820       default: fatal("unexpected call bytecode");
 821       }
 822     } else {
 823       switch (bc()) {
 824       case Bytecodes::_invokevirtual:   increment_counter(SharedRuntime::nof_normal_calls_addr()); break;
 825       case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_interface_calls_addr()); break;
 826       case Bytecodes::_invokestatic:
 827       case Bytecodes::_invokedynamic:
 828       case Bytecodes::_invokespecial:   increment_counter(SharedRuntime::nof_static_calls_addr()); break;
 829       default: fatal("unexpected call bytecode");
 830       }
 831     }
 832   }
 833 }
 834 #endif //PRODUCT
 835 
 836 
 837 // Identify possible target method and inlining style
 838 ciMethod* Parse::optimize_inlining(ciMethod* caller, int bci, ciInstanceKlass* klass,
 839                                    ciMethod *dest_method, const TypeOopPtr* receiver_type) {
 840   // only use for virtual or interface calls
 841 
 842   // If it is obviously final, do not bother to call find_monomorphic_target,
 843   // because the class hierarchy checks are not needed, and may fail due to
 844   // incompletely loaded classes.  Since we do our own class loading checks
 845   // in this module, we may confidently bind to any method.
 846   if (dest_method->can_be_statically_bound()) {
 847     return dest_method;
 848   }
 849 
 850   // Attempt to improve the receiver
 851   bool actual_receiver_is_exact = false;
 852   ciInstanceKlass* actual_receiver = klass;
 853   if (receiver_type != NULL) {
 854     // Array methods are all inherited from Object, and are monomorphic.
 855     if (receiver_type->isa_aryptr() &&
 856         dest_method->holder() == env()->Object_klass()) {
 857       return dest_method;
 858     }
 859 
 860     // All other interesting cases are instance klasses.
 861     if (!receiver_type->isa_instptr()) {
 862       return NULL;
 863     }
 864 
 865     ciInstanceKlass *ikl = receiver_type->klass()->as_instance_klass();
 866     if (ikl->is_loaded() && ikl->is_initialized() && !ikl->is_interface() &&
 867         (ikl == actual_receiver || ikl->is_subtype_of(actual_receiver))) {
 868       // ikl is a same or better type than the original actual_receiver,
 869       // e.g. static receiver from bytecodes.
 870       actual_receiver = ikl;
 871       // Is the actual_receiver exact?
 872       actual_receiver_is_exact = receiver_type->klass_is_exact();
 873     }
 874   }
 875 
 876   ciInstanceKlass*   calling_klass = caller->holder();
 877   ciMethod* cha_monomorphic_target = dest_method->find_monomorphic_target(calling_klass, klass, actual_receiver);
 878   if (cha_monomorphic_target != NULL) {
 879     assert(!cha_monomorphic_target->is_abstract(), "");
 880     // Look at the method-receiver type.  Does it add "too much information"?
 881     ciKlass*    mr_klass = cha_monomorphic_target->holder();
 882     const Type* mr_type  = TypeInstPtr::make(TypePtr::BotPTR, mr_klass);
 883     if (receiver_type == NULL || !receiver_type->higher_equal(mr_type)) {
 884       // Calling this method would include an implicit cast to its holder.
 885       // %%% Not yet implemented.  Would throw minor asserts at present.
 886       // %%% The most common wins are already gained by +UseUniqueSubclasses.
 887       // To fix, put the higher_equal check at the call of this routine,
 888       // and add a CheckCastPP to the receiver.
 889       if (TraceDependencies) {
 890         tty->print_cr("found unique CHA method, but could not cast up");
 891         tty->print("  method  = ");
 892         cha_monomorphic_target->print();
 893         tty->cr();
 894       }
 895       if (C->log() != NULL) {
 896         C->log()->elem("missed_CHA_opportunity klass='%d' method='%d'",
 897                        C->log()->identify(klass),
 898                        C->log()->identify(cha_monomorphic_target));
 899       }
 900       cha_monomorphic_target = NULL;
 901     }
 902   }
 903   if (cha_monomorphic_target != NULL) {
 904     // Hardwiring a virtual.
 905     // If we inlined because CHA revealed only a single target method,
 906     // then we are dependent on that target method not getting overridden
 907     // by dynamic class loading.  Be sure to test the "static" receiver
 908     // dest_method here, as opposed to the actual receiver, which may
 909     // falsely lead us to believe that the receiver is final or private.
 910     C->dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target);
 911     return cha_monomorphic_target;
 912   }
 913 
 914   // If the type is exact, we can still bind the method w/o a vcall.
 915   // (This case comes after CHA so we can see how much extra work it does.)
 916   if (actual_receiver_is_exact) {
 917     // In case of evolution, there is a dependence on every inlined method, since each
 918     // such method can be changed when its class is redefined.
 919     ciMethod* exact_method = dest_method->resolve_invoke(calling_klass, actual_receiver);
 920     if (exact_method != NULL) {
 921 #ifndef PRODUCT
 922       if (PrintOpto) {
 923         tty->print("  Calling method via exact type @%d --- ", bci);
 924         exact_method->print_name();
 925         tty->cr();
 926       }
 927 #endif
 928       return exact_method;
 929     }
 930   }
 931 
 932   return NULL;
 933 }