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