1 /*
2 * Copyright (c) 1998, 2026, 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 "ci/ciCallSite.hpp"
26 #include "ci/ciMethodHandle.hpp"
27 #include "ci/ciSymbols.hpp"
28 #include "classfile/vmIntrinsics.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "compiler/compileBroker.hpp"
31 #include "compiler/compileLog.hpp"
32 #include "interpreter/linkResolver.hpp"
33 #include "jvm_io.h"
34 #include "logging/log.hpp"
35 #include "logging/logLevel.hpp"
36 #include "logging/logMessage.hpp"
37 #include "logging/logStream.hpp"
38 #include "opto/addnode.hpp"
39 #include "opto/callGenerator.hpp"
40 #include "opto/castnode.hpp"
41 #include "opto/cfgnode.hpp"
42 #include "opto/inlinetypenode.hpp"
43 #include "opto/mulnode.hpp"
44 #include "opto/parse.hpp"
45 #include "opto/rootnode.hpp"
46 #include "opto/runtime.hpp"
47 #include "opto/subnode.hpp"
48 #include "prims/methodHandles.hpp"
49 #include "runtime/sharedRuntime.hpp"
50 #include "utilities/macros.hpp"
51 #include "utilities/ostream.hpp"
52 #if INCLUDE_JFR
53 #include "jfr/jfr.hpp"
54 #endif
55
56 static void print_trace_type_profile(outputStream* out, int depth, ciKlass* prof_klass, int site_count, int receiver_count,
57 bool with_deco) {
58 if (with_deco) {
59 CompileTask::print_inline_indent(depth, out);
60 }
61 out->print(" \\-> TypeProfile (%d/%d counts) = ", receiver_count, site_count);
62 prof_klass->name()->print_symbol_on(out);
63 if (with_deco) {
64 out->cr();
65 }
66 }
67
68 static void trace_type_profile(Compile* C, ciMethod* method, JVMState* jvms,
69 ciMethod* prof_method, ciKlass* prof_klass, int site_count, int receiver_count) {
70 int depth = jvms->depth() - 1;
71 int bci = jvms->bci();
72 if (TraceTypeProfile || C->print_inlining()) {
73 if (!C->print_inlining()) {
74 if (!PrintOpto && !PrintCompilation) {
75 method->print_short_name();
76 tty->cr();
77 }
78 CompileTask::print_inlining_tty(prof_method, depth, bci, InliningResult::SUCCESS);
79 print_trace_type_profile(tty, depth, prof_klass, site_count, receiver_count, true);
80 } else {
81 auto stream = C->inline_printer()->record(method, jvms, InliningResult::SUCCESS);
82 print_trace_type_profile(stream, depth, prof_klass, site_count, receiver_count, false);
83 }
84 }
85
86 LogTarget(Debug, jit, inlining) lt;
87 if (lt.is_enabled()) {
88 LogStream ls(lt);
89 print_trace_type_profile(&ls, depth, prof_klass, site_count, receiver_count, true);
90 }
91 }
92
93 CallGenerator* Compile::call_generator(ciMethod* callee, int vtable_index, bool call_does_dispatch,
94 JVMState* jvms, bool allow_inline,
95 float prof_factor, ciKlass* speculative_receiver_type,
96 bool allow_intrinsics) {
97 assert(callee != nullptr, "failed method resolution");
98
99 ciMethod* caller = jvms->method();
100 int bci = jvms->bci();
101 Bytecodes::Code bytecode = caller->java_code_at_bci(bci);
102 ciMethod* orig_callee = caller->get_method_at_bci(bci);
103
104 const bool is_virtual = (bytecode == Bytecodes::_invokevirtual) || (orig_callee->intrinsic_id() == vmIntrinsics::_linkToVirtual);
105 const bool is_interface = (bytecode == Bytecodes::_invokeinterface) || (orig_callee->intrinsic_id() == vmIntrinsics::_linkToInterface);
106 const bool is_virtual_or_interface = is_virtual || is_interface;
107
108 const bool check_access = !orig_callee->is_method_handle_intrinsic(); // method handle intrinsics don't perform access checks
109
110 // Dtrace currently doesn't work unless all calls are vanilla
111 if (env()->dtrace_method_probes()) {
112 allow_inline = false;
113 }
114
115 // Note: When we get profiling during stage-1 compiles, we want to pull
116 // from more specific profile data which pertains to this inlining.
117 // Right now, ignore the information in jvms->caller(), and do method[bci].
118 ciCallProfile profile = caller->call_profile_at_bci(bci);
119
120 // See how many times this site has been invoked.
121 int site_count = profile.count();
122 int receiver_count = -1;
123 if (call_does_dispatch && UseTypeProfile && profile.has_receiver(0)) {
124 // Receivers in the profile structure are ordered by call counts
125 // so that the most called (major) receiver is profile.receiver(0).
126 receiver_count = profile.receiver_count(0);
127 }
128
129 CompileLog* log = this->log();
130 if (log != nullptr) {
131 int rid = (receiver_count >= 0)? log->identify(profile.receiver(0)): -1;
132 int r2id = (rid != -1 && profile.has_receiver(1))? log->identify(profile.receiver(1)):-1;
133 log->begin_elem("call method='%d' count='%d' prof_factor='%f'",
134 log->identify(callee), site_count, prof_factor);
135 if (call_does_dispatch) log->print(" virtual='1'");
136 if (allow_inline) log->print(" inline='1'");
137 if (receiver_count >= 0) {
138 log->print(" receiver='%d' receiver_count='%d'", rid, receiver_count);
139 if (profile.has_receiver(1)) {
140 log->print(" receiver2='%d' receiver2_count='%d'", r2id, profile.receiver_count(1));
141 }
142 }
143 if (callee->is_method_handle_intrinsic()) {
144 log->print(" method_handle_intrinsic='1'");
145 }
146 log->end_elem();
147 }
148
149 // Special case the handling of certain common, profitable library
150 // methods. If these methods are replaced with specialized code,
151 // then we return it as the inlined version of the call.
152 CallGenerator* cg_intrinsic = nullptr;
153 if (allow_inline && allow_intrinsics) {
154 CallGenerator* cg = find_intrinsic(callee, call_does_dispatch);
155 if (cg != nullptr) {
156 if (cg->is_predicated()) {
157 // Code without intrinsic but, hopefully, inlined.
158 CallGenerator* inline_cg = this->call_generator(callee,
159 vtable_index, call_does_dispatch, jvms, allow_inline, prof_factor, speculative_receiver_type, false);
160 if (inline_cg != nullptr) {
161 cg = CallGenerator::for_predicated_intrinsic(cg, inline_cg);
162 }
163 }
164
165 // If intrinsic does the virtual dispatch, we try to use the type profile
166 // first, and hopefully inline it as the regular virtual call below.
167 // We will retry the intrinsic if nothing had claimed it afterwards.
168 if (cg->does_virtual_dispatch()) {
169 cg_intrinsic = cg;
170 cg = nullptr;
171 } else if (IncrementalInline && should_delay_vector_inlining(callee, jvms)) {
172 return CallGenerator::for_late_inline(callee, cg);
173 } else {
174 return cg;
175 }
176 }
177 }
178
179 // Do method handle calls.
180 // NOTE: This must happen before normal inlining logic below since
181 // MethodHandle.invoke* are native methods which obviously don't
182 // have bytecodes and so normal inlining fails.
183 if (callee->is_method_handle_intrinsic()) {
184 CallGenerator* cg = CallGenerator::for_method_handle_call(jvms, caller, callee, allow_inline);
185 return cg;
186 }
187
188 // Attempt to inline...
189 if (allow_inline) {
190 // The profile data is only partly attributable to this caller,
191 // scale back the call site information.
192 float past_uses = jvms->method()->scale_count(site_count, prof_factor);
193 // This is the number of times we expect the call code to be used.
194 float expected_uses = past_uses;
195
196 // Try inlining a bytecoded method:
197 if (!call_does_dispatch) {
198 InlineTree* ilt = InlineTree::find_subtree_from_root(this->ilt(), jvms->caller(), jvms->method());
199 bool should_delay = C->should_delay_inlining() || C->directive()->should_delay_inline(callee);
200 if (ilt->ok_to_inline(callee, jvms, profile, should_delay)) {
201 CallGenerator* cg = CallGenerator::for_inline(callee, expected_uses);
202 // For optimized virtual calls assert at runtime that receiver object
203 // is a subtype of the inlined method holder. CHA can report a method
204 // as a unique target under an abstract method, but receiver type
205 // sometimes has a broader type. Similar scenario is possible with
206 // default methods when type system loses information about implemented
207 // interfaces.
208 if (cg != nullptr && is_virtual_or_interface && !callee->is_static()) {
209 CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,
210 Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);
211
212 cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);
213 }
214 if (cg != nullptr) {
215 // Delay the inlining of this method to give us the
216 // opportunity to perform some high level optimizations
217 // first.
218 if (should_delay) {
219 return CallGenerator::for_late_inline(callee, cg);
220 } else if (should_delay_string_inlining(callee, jvms)) {
221 return CallGenerator::for_string_late_inline(callee, cg);
222 } else if (should_delay_boxing_inlining(callee, jvms)) {
223 return CallGenerator::for_boxing_late_inline(callee, cg);
224 } else if (should_delay_vector_reboxing_inlining(callee, jvms)) {
225 return CallGenerator::for_vector_reboxing_late_inline(callee, cg);
226 } else {
227 return cg;
228 }
229 }
230 }
231 }
232
233 // Try using the type profile.
234 if (call_does_dispatch && site_count > 0 && UseTypeProfile) {
235 // The major receiver's count >= TypeProfileMajorReceiverPercent of site_count.
236 bool have_major_receiver = profile.has_receiver(0) && (100.*profile.receiver_prob(0) >= (float)TypeProfileMajorReceiverPercent);
237 ciMethod* receiver_method = nullptr;
238
239 int morphism = profile.morphism();
240 if (speculative_receiver_type != nullptr) {
241 if (!too_many_traps_or_recompiles(caller, bci, Deoptimization::Reason_speculate_class_check)) {
242 // We have a speculative type, we should be able to resolve
243 // the call. We do that before looking at the profiling at
244 // this invoke because it may lead to bimorphic inlining which
245 // a speculative type should help us avoid.
246 receiver_method = callee->resolve_invoke(jvms->method()->holder(),
247 speculative_receiver_type,
248 check_access);
249 if (receiver_method == nullptr) {
250 speculative_receiver_type = nullptr;
251 } else {
252 morphism = 1;
253 }
254 } else {
255 // speculation failed before. Use profiling at the call
256 // (could allow bimorphic inlining for instance).
257 speculative_receiver_type = nullptr;
258 }
259 }
260 if (receiver_method == nullptr &&
261 (have_major_receiver || morphism == 1 ||
262 (morphism == 2 && UseBimorphicInlining))) {
263 // receiver_method = profile.method();
264 // Profiles do not suggest methods now. Look it up in the major receiver.
265 assert(check_access, "required");
266 receiver_method = callee->resolve_invoke(jvms->method()->holder(),
267 profile.receiver(0));
268 }
269 if (receiver_method != nullptr) {
270 // The single majority receiver sufficiently outweighs the minority.
271 CallGenerator* hit_cg = this->call_generator(receiver_method,
272 vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);
273 if (hit_cg != nullptr) {
274 // Look up second receiver.
275 CallGenerator* next_hit_cg = nullptr;
276 ciMethod* next_receiver_method = nullptr;
277 if (morphism == 2 && UseBimorphicInlining) {
278 assert(check_access, "required");
279 next_receiver_method = callee->resolve_invoke(jvms->method()->holder(),
280 profile.receiver(1));
281 if (next_receiver_method != nullptr) {
282 next_hit_cg = this->call_generator(next_receiver_method,
283 vtable_index, !call_does_dispatch, jvms,
284 allow_inline, prof_factor);
285 if (next_hit_cg != nullptr && !next_hit_cg->is_inline() &&
286 have_major_receiver && UseOnlyInlinedBimorphic) {
287 // Skip if we can't inline second receiver's method
288 next_hit_cg = nullptr;
289 }
290 }
291 }
292 CallGenerator* miss_cg;
293 Deoptimization::DeoptReason reason = (morphism == 2
294 ? Deoptimization::Reason_bimorphic
295 : Deoptimization::reason_class_check(speculative_receiver_type != nullptr));
296 if ((morphism == 1 || (morphism == 2 && next_hit_cg != nullptr)) &&
297 !too_many_traps_or_recompiles(caller, bci, reason)
298 ) {
299 // Generate uncommon trap for class check failure path
300 // in case of monomorphic or bimorphic virtual call site.
301 miss_cg = CallGenerator::for_uncommon_trap(callee, reason,
302 Deoptimization::Action_maybe_recompile);
303 } else {
304 // Generate virtual call for class check failure path
305 // in case of polymorphic virtual call site.
306 miss_cg = (IncrementalInlineVirtual ? CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor)
307 : CallGenerator::for_virtual_call(callee, vtable_index));
308 }
309 if (miss_cg != nullptr) {
310 if (next_hit_cg != nullptr) {
311 assert(speculative_receiver_type == nullptr, "shouldn't end up here if we used speculation");
312 trace_type_profile(C, jvms->method(), jvms, next_receiver_method, profile.receiver(1), site_count, profile.receiver_count(1));
313 // We don't need to record dependency on a receiver here and below.
314 // Whenever we inline, the dependency is added by Parse::Parse().
315 miss_cg = CallGenerator::for_predicted_call(profile.receiver(1), miss_cg, next_hit_cg, PROB_MAX);
316 }
317 if (miss_cg != nullptr) {
318 ciKlass* k = speculative_receiver_type != nullptr ? speculative_receiver_type : profile.receiver(0);
319 trace_type_profile(C, jvms->method(), jvms, receiver_method, k, site_count, receiver_count);
320 float hit_prob = speculative_receiver_type != nullptr ? 1.0 : profile.receiver_prob(0);
321 CallGenerator* cg = CallGenerator::for_predicted_call(k, miss_cg, hit_cg, hit_prob);
322 if (cg != nullptr) {
323 return cg;
324 }
325 }
326 }
327 }
328 }
329 }
330
331 // If there is only one implementor of this interface then we
332 // may be able to bind this invoke directly to the implementing
333 // klass but we need both a dependence on the single interface
334 // and on the method we bind to. Additionally since all we know
335 // about the receiver type is that it's supposed to implement the
336 // interface we have to insert a check that it's the class we
337 // expect. Interface types are not checked by the verifier so
338 // they are roughly equivalent to Object.
339 // The number of implementors for declared_interface is less or
340 // equal to the number of implementors for target->holder() so
341 // if number of implementors of target->holder() == 1 then
342 // number of implementors for decl_interface is 0 or 1. If
343 // it's 0 then no class implements decl_interface and there's
344 // no point in inlining.
345 if (call_does_dispatch && is_interface) {
346 ciInstanceKlass* declared_interface = nullptr;
347 if (orig_callee->intrinsic_id() == vmIntrinsics::_linkToInterface) {
348 // MemberName doesn't keep information about resolved interface class (REFC) once
349 // resolution is over, but resolved method holder (DECC) can be used as a
350 // conservative approximation.
351 declared_interface = callee->holder();
352 } else {
353 assert(!orig_callee->is_method_handle_intrinsic(), "not allowed");
354 declared_interface = caller->get_declared_method_holder_at_bci(bci)->as_instance_klass();
355 }
356 assert(declared_interface->is_interface(), "required");
357 ciInstanceKlass* singleton = declared_interface->unique_implementor();
358
359 if (singleton != nullptr) {
360 assert(singleton != declared_interface, "not a unique implementor");
361
362 ciMethod* cha_monomorphic_target =
363 callee->find_monomorphic_target(caller->holder(), declared_interface, singleton, check_access);
364
365 if (cha_monomorphic_target != nullptr &&
366 cha_monomorphic_target->holder() != env()->Object_klass()) { // subtype check against Object is useless
367 ciKlass* holder = cha_monomorphic_target->holder();
368
369 // Try to inline the method found by CHA. Inlined method is guarded by the type check.
370 CallGenerator* hit_cg = call_generator(cha_monomorphic_target,
371 vtable_index, !call_does_dispatch, jvms, allow_inline, prof_factor);
372
373 // Deoptimize on type check fail. The interpreter will throw ICCE for us.
374 CallGenerator* miss_cg = CallGenerator::for_uncommon_trap(callee,
375 Deoptimization::Reason_class_check, Deoptimization::Action_none);
376
377 ciKlass* constraint = (holder->is_subclass_of(singleton) ? holder : singleton); // avoid upcasts
378 CallGenerator* cg = CallGenerator::for_guarded_call(constraint, miss_cg, hit_cg);
379 if (hit_cg != nullptr && cg != nullptr) {
380 dependencies()->assert_unique_implementor(declared_interface, singleton);
381 dependencies()->assert_unique_concrete_method(declared_interface, cha_monomorphic_target, declared_interface, callee);
382 return cg;
383 }
384 }
385 }
386 } // call_does_dispatch && is_interface
387
388 // Nothing claimed the intrinsic, we go with straight-forward inlining
389 // for already discovered intrinsic.
390 if (allow_intrinsics && cg_intrinsic != nullptr) {
391 assert(cg_intrinsic->does_virtual_dispatch(), "sanity");
392 return cg_intrinsic;
393 }
394 } // allow_inline
395
396 // There was no special inlining tactic, or it bailed out.
397 // Use a more generic tactic, like a simple call.
398 if (call_does_dispatch) {
399 const char* msg = "virtual call";
400 C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
401 C->log_inline_failure(msg);
402 if (IncrementalInlineVirtual && allow_inline) {
403 return CallGenerator::for_late_inline_virtual(callee, vtable_index, prof_factor); // attempt to inline through virtual call later
404 } else {
405 return CallGenerator::for_virtual_call(callee, vtable_index);
406 }
407 } else {
408 // Class Hierarchy Analysis or Type Profile reveals a unique target, or it is a static or special call.
409 CallGenerator* cg = CallGenerator::for_direct_call(callee, should_delay_inlining(callee, jvms));
410 // For optimized virtual calls assert at runtime that receiver object
411 // is a subtype of the method holder.
412 if (cg != nullptr && is_virtual_or_interface && !callee->is_static()) {
413 CallGenerator* trap_cg = CallGenerator::for_uncommon_trap(callee,
414 Deoptimization::Reason_receiver_constraint, Deoptimization::Action_none);
415 cg = CallGenerator::for_guarded_call(callee->holder(), trap_cg, cg);
416 }
417 return cg;
418 }
419 }
420
421 // Return true for methods that shouldn't be inlined early so that
422 // they are easier to analyze and optimize as intrinsics.
423 bool Compile::should_delay_string_inlining(ciMethod* call_method, JVMState* jvms) {
424 if (has_stringbuilder()) {
425
426 if ((call_method->holder() == C->env()->StringBuilder_klass() ||
427 call_method->holder() == C->env()->StringBuffer_klass()) &&
428 (jvms->method()->holder() == C->env()->StringBuilder_klass() ||
429 jvms->method()->holder() == C->env()->StringBuffer_klass())) {
430 // Delay SB calls only when called from non-SB code
431 return false;
432 }
433
434 switch (call_method->intrinsic_id()) {
435 case vmIntrinsics::_StringBuilder_void:
436 case vmIntrinsics::_StringBuilder_int:
437 case vmIntrinsics::_StringBuilder_String:
438 case vmIntrinsics::_StringBuilder_append_char:
439 case vmIntrinsics::_StringBuilder_append_int:
440 case vmIntrinsics::_StringBuilder_append_String:
441 case vmIntrinsics::_StringBuilder_toString:
442 case vmIntrinsics::_StringBuffer_void:
443 case vmIntrinsics::_StringBuffer_int:
444 case vmIntrinsics::_StringBuffer_String:
445 case vmIntrinsics::_StringBuffer_append_char:
446 case vmIntrinsics::_StringBuffer_append_int:
447 case vmIntrinsics::_StringBuffer_append_String:
448 case vmIntrinsics::_StringBuffer_toString:
449 case vmIntrinsics::_Integer_toString:
450 return true;
451
452 case vmIntrinsics::_String_String:
453 {
454 Node* receiver = jvms->map()->in(jvms->argoff() + 1);
455 if (receiver->is_Proj() && receiver->in(0)->is_CallStaticJava()) {
456 CallStaticJavaNode* csj = receiver->in(0)->as_CallStaticJava();
457 ciMethod* m = csj->method();
458 if (m != nullptr &&
459 (m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString ||
460 m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString))
461 // Delay String.<init>(new SB())
462 return true;
463 }
464 return false;
465 }
466
467 default:
468 return false;
469 }
470 }
471 return false;
472 }
473
474 bool Compile::should_delay_boxing_inlining(ciMethod* call_method, JVMState* jvms) {
475 if (eliminate_boxing() && call_method->is_boxing_method()) {
476 set_has_boxed_value(true);
477 return aggressive_unboxing();
478 }
479 return false;
480 }
481
482 bool Compile::should_delay_vector_inlining(ciMethod* call_method, JVMState* jvms) {
483 return EnableVectorSupport && call_method->is_vector_method();
484 }
485
486 bool Compile::should_delay_vector_reboxing_inlining(ciMethod* call_method, JVMState* jvms) {
487 return EnableVectorSupport && (call_method->intrinsic_id() == vmIntrinsics::_VectorRebox);
488 }
489
490 // uncommon-trap call-sites where callee is unloaded, uninitialized or will not link
491 bool Parse::can_not_compile_call_site(ciMethod *dest_method, ciInstanceKlass* klass) {
492 // Additional inputs to consider...
493 // bc = bc()
494 // caller = method()
495 // iter().get_method_holder_index()
496 assert( dest_method->is_loaded(), "ciTypeFlow should not let us get here" );
497 // Interface classes can be loaded & linked and never get around to
498 // being initialized. Uncommon-trap for not-initialized static or
499 // v-calls. Let interface calls happen.
500 ciInstanceKlass* holder_klass = dest_method->holder();
501 if (!holder_klass->is_being_initialized() &&
502 !holder_klass->is_initialized() &&
503 !holder_klass->is_interface()) {
504 uncommon_trap(Deoptimization::Reason_uninitialized,
505 Deoptimization::Action_reinterpret,
506 holder_klass);
507 return true;
508 }
509
510 assert(dest_method->is_loaded(), "dest_method: typeflow responsibility");
511 return false;
512 }
513
514 #ifdef ASSERT
515 static bool check_call_consistency(JVMState* jvms, CallGenerator* cg) {
516 ciMethod* symbolic_info = jvms->method()->get_method_at_bci(jvms->bci());
517 ciMethod* resolved_method = cg->method();
518 if (!ciMethod::is_consistent_info(symbolic_info, resolved_method)) {
519 tty->print_cr("JVMS:");
520 jvms->dump();
521 tty->print_cr("Bytecode info:");
522 jvms->method()->get_method_at_bci(jvms->bci())->print(); tty->cr();
523 tty->print_cr("Resolved method:");
524 cg->method()->print(); tty->cr();
525 return false;
526 }
527 return true;
528 }
529 #endif // ASSERT
530
531 //------------------------------do_call----------------------------------------
532 // Handle your basic call. Inline if we can & want to, else just setup call.
533 void Parse::do_call() {
534 // It's likely we are going to add debug info soon.
535 // Also, if we inline a guy who eventually needs debug info for this JVMS,
536 // our contribution to it is cleaned up right here.
537 kill_dead_locals();
538
539 // Set frequently used booleans
540 const bool is_virtual = bc() == Bytecodes::_invokevirtual;
541 const bool is_virtual_or_interface = is_virtual || bc() == Bytecodes::_invokeinterface;
542 const bool has_receiver = Bytecodes::has_receiver(bc());
543
544 // Find target being called
545 bool will_link;
546 ciSignature* declared_signature = nullptr;
547 ciMethod* orig_callee = iter().get_method(will_link, &declared_signature); // callee in the bytecode
548 ciInstanceKlass* holder_klass = orig_callee->holder();
549 ciKlass* holder = iter().get_declared_method_holder();
550 ciInstanceKlass* klass = ciEnv::get_instance_klass_for_declared_method_holder(holder);
551 assert(declared_signature != nullptr, "cannot be null");
552 JFR_ONLY(Jfr::on_resolution(this, holder, orig_callee);)
553
554 // Bump max node limit for JSR292 users
555 if (bc() == Bytecodes::_invokedynamic || orig_callee->is_method_handle_intrinsic()) {
556 C->set_max_node_limit(3*MaxNodeLimit);
557 }
558
559 // uncommon-trap when callee is unloaded, uninitialized or will not link
560 // bailout when too many arguments for register representation
561 if (!will_link || can_not_compile_call_site(orig_callee, klass)) {
562 if (PrintOpto && (Verbose || WizardMode)) {
563 method()->print_name(); tty->print_cr(" can not compile call at bci %d to:", bci());
564 orig_callee->print_name(); tty->cr();
565 }
566 return;
567 }
568 assert(holder_klass->is_loaded(), "");
569 //assert((bc_callee->is_static() || is_invokedynamic) == !has_receiver , "must match bc"); // XXX invokehandle (cur_bc_raw)
570 // Note: this takes into account invokeinterface of methods declared in java/lang/Object,
571 // which should be invokevirtuals but according to the VM spec may be invokeinterfaces
572 assert(holder_klass->is_interface() || holder_klass->super() == nullptr || (bc() != Bytecodes::_invokeinterface), "must match bc");
573 // Note: In the absence of miranda methods, an abstract class K can perform
574 // an invokevirtual directly on an interface method I.m if K implements I.
575
576 // orig_callee is the resolved callee which's signature includes the
577 // appendix argument.
578 const int nargs = orig_callee->arg_size();
579 const bool is_signature_polymorphic = MethodHandles::is_signature_polymorphic(orig_callee->intrinsic_id());
580
581 // Push appendix argument (MethodType, CallSite, etc.), if one.
582 if (iter().has_appendix()) {
583 ciObject* appendix_arg = iter().get_appendix();
584 const TypeOopPtr* appendix_arg_type = TypeOopPtr::make_from_constant(appendix_arg, /* require_const= */ true);
585 Node* appendix_arg_node = _gvn.makecon(appendix_arg_type);
586 push(appendix_arg_node);
587 }
588
589 // ---------------------
590 // Does Class Hierarchy Analysis reveal only a single target of a v-call?
591 // Then we may inline or make a static call, but become dependent on there being only 1 target.
592 // Does the call-site type profile reveal only one receiver?
593 // Then we may introduce a run-time check and inline on the path where it succeeds.
594 // The other path may uncommon_trap, check for another receiver, or do a v-call.
595
596 // Try to get the most accurate receiver type
597 ciMethod* callee = orig_callee;
598 int vtable_index = Method::invalid_vtable_index;
599 bool call_does_dispatch = false;
600
601 // Speculative type of the receiver if any
602 ciKlass* speculative_receiver_type = nullptr;
603 if (is_virtual_or_interface) {
604 Node* receiver_node = stack(sp() - nargs);
605 const TypeOopPtr* receiver_type = _gvn.type(receiver_node)->isa_oopptr();
606 // call_does_dispatch and vtable_index are out-parameters. They might be changed.
607 // For arrays, klass below is Object. When vtable calls are used,
608 // resolving the call with Object would allow an illegal call to
609 // finalize() on an array. We use holder instead: illegal calls to
610 // finalize() won't be compiled as vtable calls (IC call
611 // resolution will catch the illegal call) and the few legal calls
612 // on array types won't be either.
613 callee = C->optimize_virtual_call(method(), klass, holder, orig_callee,
614 receiver_type, is_virtual,
615 call_does_dispatch, vtable_index); // out-parameters
616 speculative_receiver_type = receiver_type != nullptr ? receiver_type->speculative_type() : nullptr;
617 }
618
619 // Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.
620 ciKlass* receiver_constraint = nullptr;
621 if (iter().cur_bc_raw() == Bytecodes::_invokespecial && !orig_callee->is_object_constructor()) {
622 ciInstanceKlass* calling_klass = method()->holder();
623 ciInstanceKlass* sender_klass = calling_klass;
624 if (sender_klass->is_interface()) {
625 receiver_constraint = sender_klass;
626 }
627 } else if (iter().cur_bc_raw() == Bytecodes::_invokeinterface && orig_callee->is_private()) {
628 assert(holder->is_interface(), "How did we get a non-interface method here!");
629 receiver_constraint = holder;
630 }
631
632 if (receiver_constraint != nullptr) {
633 Node* receiver_node = stack(sp() - nargs);
634 Node* cls_node = makecon(TypeKlassPtr::make(receiver_constraint, Type::trust_interfaces));
635 Node* bad_type_ctrl = nullptr;
636 Node* casted_receiver = gen_checkcast(receiver_node, cls_node, &bad_type_ctrl);
637 if (bad_type_ctrl != nullptr) {
638 PreserveJVMState pjvms(this);
639 set_control(bad_type_ctrl);
640 uncommon_trap(Deoptimization::Reason_class_check,
641 Deoptimization::Action_none);
642 }
643 if (stopped()) {
644 return; // MUST uncommon-trap?
645 }
646 set_stack(sp() - nargs, casted_receiver);
647 }
648
649 // Note: It's OK to try to inline a virtual call.
650 // The call generator will not attempt to inline a polymorphic call
651 // unless it knows how to optimize the receiver dispatch.
652 bool try_inline = (C->do_inlining() || InlineAccessors);
653
654 // ---------------------
655 dec_sp(nargs); // Temporarily pop args for JVM state of call
656 JVMState* jvms = sync_jvms();
657
658 // ---------------------
659 // Decide call tactic.
660 // This call checks with CHA, the interpreter profile, intrinsics table, etc.
661 // It decides whether inlining is desirable or not.
662 CallGenerator* cg = C->call_generator(callee, vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type);
663 if (failing()) {
664 return;
665 }
666 assert(cg != nullptr, "must find a CallGenerator for callee %s", callee->name()->as_utf8());
667
668 // NOTE: Don't use orig_callee and callee after this point! Use cg->method() instead.
669 orig_callee = callee = nullptr;
670
671 // ---------------------
672
673 // Feed profiling data for arguments to the type system so it can
674 // propagate it as speculative types
675 record_profiled_arguments_for_speculation(cg->method(), bc());
676
677 #ifndef PRODUCT
678 // bump global counters for calls
679 count_compiled_calls(/*at_method_entry*/ false, cg->is_inline());
680
681 // Record first part of parsing work for this call
682 parse_histogram()->record_change();
683 #endif // not PRODUCT
684
685 assert(jvms == this->jvms(), "still operating on the right JVMS");
686 assert(jvms_in_sync(), "jvms must carry full info into CG");
687
688 // save across call, for a subsequent cast_not_null.
689 Node* receiver = has_receiver ? argument(0) : nullptr;
690
691 // The extra CheckCastPPs for speculative types mess with PhaseStringOpts
692 if (receiver != nullptr && !call_does_dispatch && !cg->is_string_late_inline()) {
693 // Feed profiling data for a single receiver to the type system so
694 // it can propagate it as a speculative type
695 receiver = record_profiled_receiver_for_speculation(receiver);
696 }
697
698 JVMState* new_jvms = cg->generate(jvms);
699 if (new_jvms == nullptr) {
700 // When inlining attempt fails (e.g., too many arguments),
701 // it may contaminate the current compile state, making it
702 // impossible to pull back and try again. Once we call
703 // cg->generate(), we are committed. If it fails, the whole
704 // compilation task is compromised.
705 if (failing()) return;
706
707 // This can happen if a library intrinsic is available, but refuses
708 // the call site, perhaps because it did not match a pattern the
709 // intrinsic was expecting to optimize. Should always be possible to
710 // get a normal java call that may inline in that case
711 cg = C->call_generator(cg->method(), vtable_index, call_does_dispatch, jvms, try_inline, prof_factor(), speculative_receiver_type, /* allow_intrinsics= */ false);
712 new_jvms = cg->generate(jvms);
713 if (new_jvms == nullptr) {
714 guarantee(failing(), "call failed to generate: calls should work");
715 return;
716 }
717 }
718
719 if (cg->is_inline()) {
720 // Accumulate has_loops estimate
721 C->env()->notice_inlined_method(cg->method());
722 }
723
724 // Reset parser state from [new_]jvms, which now carries results of the call.
725 // Return value (if any) is already pushed on the stack by the cg.
726 add_exception_states_from(new_jvms);
727 if (new_jvms->map()->control() == top()) {
728 stop_and_kill_map();
729 } else {
730 assert(new_jvms->same_calls_as(jvms), "method/bci left unchanged");
731 set_jvms(new_jvms);
732 }
733
734 assert(check_call_consistency(jvms, cg), "inconsistent info");
735
736 if (!stopped()) {
737 // This was some sort of virtual call, which did a null check for us.
738 // Now we can assert receiver-not-null, on the normal return path.
739 if (receiver != nullptr && cg->is_virtual()) {
740 Node* cast = cast_not_null(receiver);
741 // %%% assert(receiver == cast, "should already have cast the receiver");
742 }
743
744 ciType* rtype = cg->method()->return_type();
745 ciType* ctype = declared_signature->return_type();
746
747 if (Bytecodes::has_optional_appendix(iter().cur_bc_raw()) || is_signature_polymorphic) {
748 // Be careful here with return types.
749 if (ctype != rtype) {
750 BasicType rt = rtype->basic_type();
751 BasicType ct = ctype->basic_type();
752 if (ct == T_VOID) {
753 // It's OK for a method to return a value that is discarded.
754 // The discarding does not require any special action from the caller.
755 // The Java code knows this, at VerifyType.isNullConversion.
756 pop_node(rt); // whatever it was, pop it
757 } else if (rt == T_INT || is_subword_type(rt)) {
758 // Nothing. These cases are handled in lambda form bytecode.
759 assert(ct == T_INT || is_subword_type(ct), "must match: rt=%s, ct=%s", type2name(rt), type2name(ct));
760 } else if (is_reference_type(rt)) {
761 assert(is_reference_type(ct), "rt=%s, ct=%s", type2name(rt), type2name(ct));
762 if (ctype->is_loaded()) {
763 const TypeOopPtr* arg_type = TypeOopPtr::make_from_klass(rtype->as_klass());
764 const Type* sig_type = TypeOopPtr::make_from_klass(ctype->as_klass());
765 if (arg_type != nullptr && !arg_type->higher_equal(sig_type)) {
766 Node* retnode = pop();
767 Node* cast_obj = _gvn.transform(new CheckCastPPNode(control(), retnode, sig_type));
768 push(cast_obj);
769 }
770 }
771 } else {
772 assert(rt == ct, "unexpected mismatch: rt=%s, ct=%s", type2name(rt), type2name(ct));
773 // push a zero; it's better than getting an oop/int mismatch
774 pop_node(rt);
775 Node* retnode = zerocon(ct);
776 push_node(ct, retnode);
777 }
778 // Now that the value is well-behaved, continue with the call-site type.
779 rtype = ctype;
780 }
781 } else {
782 // Symbolic resolution enforces the types to be the same.
783 // NOTE: We must relax the assert for unloaded types because two
784 // different ciType instances of the same unloaded class type
785 // can appear to be "loaded" by different loaders (depending on
786 // the accessing class).
787 assert(!rtype->is_loaded() || !ctype->is_loaded() || rtype == ctype,
788 "mismatched return types: rtype=%s, ctype=%s", rtype->name(), ctype->name());
789 }
790
791 // If the return type of the method is not loaded, assert that the
792 // value we got is a null. Otherwise, we need to recompile.
793 if (!rtype->is_loaded()) {
794 if (PrintOpto && (Verbose || WizardMode)) {
795 method()->print_name(); tty->print_cr(" asserting nullness of result at bci: %d", bci());
796 cg->method()->print_name(); tty->cr();
797 }
798 if (C->log() != nullptr) {
799 C->log()->elem("assert_null reason='return' klass='%d'",
800 C->log()->identify(rtype));
801 }
802 // If there is going to be a trap, put it at the next bytecode:
803 set_bci(iter().next_bci());
804 null_assert(peek());
805 set_bci(iter().cur_bci()); // put it back
806 }
807 BasicType ct = ctype->basic_type();
808 if (is_reference_type(ct)) {
809 record_profiled_return_for_speculation();
810 }
811
812 if (!rtype->is_void()) {
813 Node* retnode = peek();
814 const Type* rettype = gvn().type(retnode);
815 if (!cg->method()->return_value_is_larval() && !retnode->is_InlineType() && rettype->is_inlinetypeptr()) {
816 retnode = InlineTypeNode::make_from_oop(this, retnode, rettype->inline_klass());
817 dec_sp(1);
818 push(retnode);
819 }
820 }
821
822 if (cg->method()->receiver_maybe_larval() && receiver != nullptr &&
823 !receiver->is_InlineType() && gvn().type(receiver)->is_inlinetypeptr()) {
824 InlineTypeNode* non_larval = InlineTypeNode::make_from_oop(this, receiver, gvn().type(receiver)->inline_klass());
825 // Relinquish the oop input, we will delay the allocation to the point it is needed, see the
826 // comments in InlineTypeNode::Ideal for more details
827 non_larval = non_larval->clone_if_required(&gvn(), nullptr);
828 non_larval->set_oop(gvn(), null());
829 non_larval->set_is_buffered(gvn(), false);
830 non_larval = gvn().transform(non_larval)->as_InlineType();
831 map()->replace_edge(receiver, non_larval);
832 }
833 }
834
835 // Restart record of parsing work after possible inlining of call
836 #ifndef PRODUCT
837 parse_histogram()->set_initial_state(bc());
838 #endif
839 }
840
841 //---------------------------catch_call_exceptions-----------------------------
842 // Put a Catch and CatchProj nodes behind a just-created call.
843 // Send their caught exceptions to the proper handler.
844 // This may be used after a call to the rethrow VM stub,
845 // when it is needed to process unloaded exception classes.
846 void Parse::catch_call_exceptions(ciExceptionHandlerStream& handlers) {
847 // Exceptions are delivered through this channel:
848 Node* i_o = this->i_o();
849
850 // Add a CatchNode.
851 Arena tmp_mem{mtCompiler};
852 GrowableArray<int> bcis(&tmp_mem, 8, 0, -1);
853 GrowableArray<const Type*> extypes(&tmp_mem, 8, 0, nullptr);
854 GrowableArray<int> saw_unloaded(&tmp_mem, 8, 0, -1);
855
856 bool default_handler = false;
857 for (; !handlers.is_done(); handlers.next()) {
858 ciExceptionHandler* h = handlers.handler();
859 int h_bci = h->handler_bci();
860 ciInstanceKlass* h_klass = h->is_catch_all() ? env()->Throwable_klass() : h->catch_klass();
861 // Do not introduce unloaded exception types into the graph:
862 if (!h_klass->is_loaded()) {
863 if (saw_unloaded.contains(h_bci)) {
864 /* We've already seen an unloaded exception with h_bci,
865 so don't duplicate. Duplication will cause the CatchNode to be
866 unnecessarily large. See 4713716. */
867 continue;
868 } else {
869 saw_unloaded.append(h_bci);
870 }
871 }
872 const Type* h_extype = TypeOopPtr::make_from_klass(h_klass);
873 // (We use make_from_klass because it respects UseUniqueSubclasses.)
874 h_extype = h_extype->join(TypeInstPtr::NOTNULL);
875 assert(!h_extype->empty(), "sanity");
876 // Note: It's OK if the BCIs repeat themselves.
877 bcis.append(h_bci);
878 extypes.append(h_extype);
879 if (h_bci == -1) {
880 default_handler = true;
881 }
882 }
883
884 if (!default_handler) {
885 bcis.append(-1);
886 const Type* extype = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr();
887 extype = extype->join(TypeInstPtr::NOTNULL);
888 extypes.append(extype);
889 }
890
891 int len = bcis.length();
892 CatchNode *cn = new CatchNode(control(), i_o, len+1);
893 Node *catch_ = _gvn.transform(cn);
894
895 // now branch with the exception state to each of the (potential)
896 // handlers
897 for(int i=0; i < len; i++) {
898 // Setup JVM state to enter the handler.
899 PreserveJVMState pjvms(this);
900 // Locals are just copied from before the call.
901 // Get control from the CatchNode.
902 int handler_bci = bcis.at(i);
903 Node* ctrl = _gvn.transform( new CatchProjNode(catch_, i+1,handler_bci));
904 // This handler cannot happen?
905 if (ctrl == top()) continue;
906 set_control(ctrl);
907
908 // Create exception oop
909 const TypeInstPtr* extype = extypes.at(i)->is_instptr();
910 Node* ex_oop = _gvn.transform(new CreateExNode(extypes.at(i), ctrl, i_o));
911
912 // Handle unloaded exception classes.
913 if (saw_unloaded.contains(handler_bci)) {
914 // An unloaded exception type is coming here. Do an uncommon trap.
915 #ifndef PRODUCT
916 // We do not expect the same handler bci to take both cold unloaded
917 // and hot loaded exceptions. But, watch for it.
918 if (PrintOpto && (Verbose || WizardMode) && extype->is_loaded()) {
919 tty->print("Warning: Handler @%d takes mixed loaded/unloaded exceptions in ", bci());
920 method()->print_name(); tty->cr();
921 } else if (PrintOpto && (Verbose || WizardMode)) {
922 tty->print("Bailing out on unloaded exception type ");
923 extype->instance_klass()->print_name();
924 tty->print(" at bci:%d in ", bci());
925 method()->print_name(); tty->cr();
926 }
927 #endif
928 // Emit an uncommon trap instead of processing the block.
929 set_bci(handler_bci);
930 push_ex_oop(ex_oop);
931 uncommon_trap(Deoptimization::Reason_unloaded,
932 Deoptimization::Action_reinterpret,
933 extype->instance_klass(), "!loaded exception");
934 set_bci(iter().cur_bci()); // put it back
935 continue;
936 }
937
938 // go to the exception handler
939 if (handler_bci < 0) { // merge with corresponding rethrow node
940 throw_to_exit(make_exception_state(ex_oop));
941 } else { // Else jump to corresponding handle
942 push_ex_oop(ex_oop); // Clear stack and push just the oop.
943 merge_exception(handler_bci);
944 }
945 }
946
947 // The first CatchProj is for the normal return.
948 // (Note: If this is a call to rethrow_Java, this node goes dead.)
949 set_control(_gvn.transform( new CatchProjNode(catch_, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci)));
950 }
951
952
953 //----------------------------catch_inline_exceptions--------------------------
954 // Handle all exceptions thrown by an inlined method or individual bytecode.
955 // Common case 1: we have no handler, so all exceptions merge right into
956 // the rethrow case.
957 // Case 2: we have some handlers, with loaded exception klasses that have
958 // no subklasses. We do a Deutsch-Schiffman style type-check on the incoming
959 // exception oop and branch to the handler directly.
960 // Case 3: We have some handlers with subklasses or are not loaded at
961 // compile-time. We have to call the runtime to resolve the exception.
962 // So we insert a RethrowCall and all the logic that goes with it.
963 void Parse::catch_inline_exceptions(SafePointNode* ex_map) {
964 // Caller is responsible for saving away the map for normal control flow!
965 assert(stopped(), "call set_map(nullptr) first");
966 assert(method()->has_exception_handlers(), "don't come here w/o work to do");
967
968 Node* ex_node = saved_ex_oop(ex_map);
969 if (ex_node == top()) {
970 // No action needed.
971 return;
972 }
973 const TypeInstPtr* ex_type = _gvn.type(ex_node)->isa_instptr();
974 NOT_PRODUCT(if (ex_type==nullptr) tty->print_cr("*** Exception not InstPtr"));
975 if (ex_type == nullptr)
976 ex_type = TypeOopPtr::make_from_klass(env()->Throwable_klass())->is_instptr();
977
978 // determine potential exception handlers
979 ciExceptionHandlerStream handlers(method(), bci(),
980 ex_type->instance_klass(),
981 ex_type->klass_is_exact());
982
983 // Start executing from the given throw state. (Keep its stack, for now.)
984 // Get the exception oop as known at compile time.
985 ex_node = use_exception_state(ex_map);
986
987 // Get the exception oop klass from its header
988 Node* ex_klass_node = nullptr;
989 if (has_exception_handler() && !ex_type->klass_is_exact()) {
990 Node* p = basic_plus_adr( ex_node, ex_node, oopDesc::klass_offset_in_bytes());
991 ex_klass_node = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
992
993 // Compute the exception klass a little more cleverly.
994 // Obvious solution is to simple do a LoadKlass from the 'ex_node'.
995 // However, if the ex_node is a PhiNode, I'm going to do a LoadKlass for
996 // each arm of the Phi. If I know something clever about the exceptions
997 // I'm loading the class from, I can replace the LoadKlass with the
998 // klass constant for the exception oop.
999 if (ex_node->is_Phi()) {
1000 ex_klass_node = new PhiNode(ex_node->in(0), TypeInstKlassPtr::OBJECT);
1001 for (uint i = 1; i < ex_node->req(); i++) {
1002 Node* ex_in = ex_node->in(i);
1003 if (ex_in == top() || ex_in == nullptr) {
1004 // This path was not taken.
1005 ex_klass_node->init_req(i, top());
1006 continue;
1007 }
1008 Node* p = basic_plus_adr(ex_in, ex_in, oopDesc::klass_offset_in_bytes());
1009 Node* k = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1010 ex_klass_node->init_req( i, k );
1011 }
1012 ex_klass_node = _gvn.transform(ex_klass_node);
1013 }
1014 }
1015
1016 // Scan the exception table for applicable handlers.
1017 // If none, we can call rethrow() and be done!
1018 // If precise (loaded with no subklasses), insert a D.S. style
1019 // pointer compare to the correct handler and loop back.
1020 // If imprecise, switch to the Rethrow VM-call style handling.
1021
1022 int remaining = handlers.count_remaining();
1023
1024 // iterate through all entries sequentially
1025 for (;!handlers.is_done(); handlers.next()) {
1026 ciExceptionHandler* handler = handlers.handler();
1027
1028 if (handler->is_rethrow()) {
1029 // If we fell off the end of the table without finding an imprecise
1030 // exception klass (and without finding a generic handler) then we
1031 // know this exception is not handled in this method. We just rethrow
1032 // the exception into the caller.
1033 throw_to_exit(make_exception_state(ex_node));
1034 return;
1035 }
1036
1037 // exception handler bci range covers throw_bci => investigate further
1038 int handler_bci = handler->handler_bci();
1039
1040 if (remaining == 1) {
1041 push_ex_oop(ex_node); // Push exception oop for handler
1042 if (PrintOpto && WizardMode) {
1043 tty->print_cr(" Catching every inline exception bci:%d -> handler_bci:%d", bci(), handler_bci);
1044 }
1045 // If this is a backwards branch in the bytecodes, add safepoint
1046 maybe_add_safepoint(handler_bci);
1047 merge_exception(handler_bci); // jump to handler
1048 return; // No more handling to be done here!
1049 }
1050
1051 // Get the handler's klass
1052 ciInstanceKlass* klass = handler->catch_klass();
1053
1054 if (!klass->is_loaded()) { // klass is not loaded?
1055 // fall through into catch_call_exceptions which will emit a
1056 // handler with an uncommon trap.
1057 break;
1058 }
1059
1060 if (klass->is_interface()) // should not happen, but...
1061 break; // bail out
1062
1063 // Check the type of the exception against the catch type
1064 const TypeKlassPtr *tk = TypeKlassPtr::make(klass);
1065 Node* con = _gvn.makecon(tk);
1066 Node* not_subtype_ctrl = gen_subtype_check(ex_klass_node, con);
1067 if (!stopped()) {
1068 PreserveJVMState pjvms(this);
1069 const TypeInstPtr* tinst = TypeOopPtr::make_from_klass_unique(klass)->cast_to_ptr_type(TypePtr::NotNull)->is_instptr();
1070 assert(klass->has_subklass() || tinst->klass_is_exact(), "lost exactness");
1071 Node* ex_oop = _gvn.transform(new CheckCastPPNode(control(), ex_node, tinst));
1072 push_ex_oop(ex_oop); // Push exception oop for handler
1073 if (PrintOpto && WizardMode) {
1074 tty->print(" Catching inline exception bci:%d -> handler_bci:%d -- ", bci(), handler_bci);
1075 klass->print_name();
1076 tty->cr();
1077 }
1078 // If this is a backwards branch in the bytecodes, add safepoint
1079 maybe_add_safepoint(handler_bci);
1080 merge_exception(handler_bci);
1081 }
1082 set_control(not_subtype_ctrl);
1083
1084 // Come here if exception does not match handler.
1085 // Carry on with more handler checks.
1086 --remaining;
1087 }
1088
1089 assert(!stopped(), "you should return if you finish the chain");
1090
1091 // Oops, need to call into the VM to resolve the klasses at runtime.
1092 kill_dead_locals();
1093
1094 { PreserveReexecuteState preexecs(this);
1095 // When throwing an exception, set the reexecute flag for deoptimization.
1096 // This is mostly needed to pass -XX:+VerifyStack sanity checks.
1097 jvms()->set_should_reexecute(true);
1098
1099 make_runtime_call(RC_NO_LEAF | RC_MUST_THROW,
1100 OptoRuntime::rethrow_Type(),
1101 OptoRuntime::rethrow_stub(),
1102 nullptr, nullptr,
1103 ex_node);
1104 }
1105
1106 // Rethrow is a pure call, no side effects, only a result.
1107 // The result cannot be allocated, so we use I_O
1108
1109 // Catch exceptions from the rethrow
1110 catch_call_exceptions(handlers);
1111 }
1112
1113
1114 // (Note: Moved add_debug_info into GraphKit::add_safepoint_edges.)
1115
1116
1117 #ifndef PRODUCT
1118 void Parse::count_compiled_calls(bool at_method_entry, bool is_inline) {
1119 if( CountCompiledCalls ) {
1120 if( at_method_entry ) {
1121 // bump invocation counter if top method (for statistics)
1122 if (CountCompiledCalls && depth() == 1) {
1123 const TypePtr* addr_type = TypeMetadataPtr::make(method());
1124 Node* adr1 = makecon(addr_type);
1125 Node* adr2 = basic_plus_adr(adr1, adr1, in_bytes(Method::compiled_invocation_counter_offset()));
1126 increment_counter(adr2);
1127 }
1128 } else if (is_inline) {
1129 switch (bc()) {
1130 case Bytecodes::_invokevirtual: increment_counter(SharedRuntime::nof_inlined_calls_addr()); break;
1131 case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_inlined_interface_calls_addr()); break;
1132 case Bytecodes::_invokestatic:
1133 case Bytecodes::_invokedynamic:
1134 case Bytecodes::_invokespecial: increment_counter(SharedRuntime::nof_inlined_static_calls_addr()); break;
1135 default: fatal("unexpected call bytecode");
1136 }
1137 } else {
1138 switch (bc()) {
1139 case Bytecodes::_invokevirtual: increment_counter(SharedRuntime::nof_normal_calls_addr()); break;
1140 case Bytecodes::_invokeinterface: increment_counter(SharedRuntime::nof_interface_calls_addr()); break;
1141 case Bytecodes::_invokestatic:
1142 case Bytecodes::_invokedynamic:
1143 case Bytecodes::_invokespecial: increment_counter(SharedRuntime::nof_static_calls_addr()); break;
1144 default: fatal("unexpected call bytecode");
1145 }
1146 }
1147 }
1148 }
1149 #endif //PRODUCT
1150
1151
1152 ciMethod* Compile::optimize_virtual_call(ciMethod* caller, ciInstanceKlass* klass,
1153 ciKlass* holder, ciMethod* callee,
1154 const TypeOopPtr* receiver_type, bool is_virtual,
1155 bool& call_does_dispatch, int& vtable_index,
1156 bool check_access) {
1157 // Set default values for out-parameters.
1158 call_does_dispatch = true;
1159 vtable_index = Method::invalid_vtable_index;
1160
1161 // Choose call strategy.
1162 ciMethod* optimized_virtual_method = optimize_inlining(caller, klass, holder, callee,
1163 receiver_type, check_access);
1164
1165 // Have the call been sufficiently improved such that it is no longer a virtual?
1166 if (optimized_virtual_method != nullptr) {
1167 callee = optimized_virtual_method;
1168 call_does_dispatch = false;
1169 } else if (!UseInlineCaches && is_virtual && callee->is_loaded()) {
1170 // We can make a vtable call at this site
1171 vtable_index = callee->resolve_vtable_index(caller->holder(), holder);
1172 }
1173 return callee;
1174 }
1175
1176 // Identify possible target method and inlining style
1177 ciMethod* Compile::optimize_inlining(ciMethod* caller, ciInstanceKlass* klass, ciKlass* holder,
1178 ciMethod* callee, const TypeOopPtr* receiver_type,
1179 bool check_access) {
1180 // only use for virtual or interface calls
1181
1182 // If it is obviously final, do not bother to call find_monomorphic_target,
1183 // because the class hierarchy checks are not needed, and may fail due to
1184 // incompletely loaded classes. Since we do our own class loading checks
1185 // in this module, we may confidently bind to any method.
1186 if (callee->can_be_statically_bound()) {
1187 return callee;
1188 }
1189
1190 if (receiver_type == nullptr) {
1191 return nullptr; // no receiver type info
1192 }
1193
1194 // Attempt to improve the receiver
1195 bool actual_receiver_is_exact = false;
1196 ciInstanceKlass* actual_receiver = klass;
1197 // Array methods are all inherited from Object, and are monomorphic.
1198 // finalize() call on array is not allowed.
1199 if (receiver_type->isa_aryptr() &&
1200 callee->holder() == env()->Object_klass() &&
1201 callee->name() != ciSymbols::finalize_method_name()) {
1202 return callee;
1203 }
1204
1205 // All other interesting cases are instance klasses.
1206 if (!receiver_type->isa_instptr()) {
1207 return nullptr;
1208 }
1209
1210 ciInstanceKlass* receiver_klass = receiver_type->is_instptr()->instance_klass();
1211 if (receiver_klass->is_loaded() && receiver_klass->is_initialized() && !receiver_klass->is_interface() &&
1212 (receiver_klass == actual_receiver || receiver_klass->is_subtype_of(actual_receiver))) {
1213 // ikl is a same or better type than the original actual_receiver,
1214 // e.g. static receiver from bytecodes.
1215 actual_receiver = receiver_klass;
1216 // Is the actual_receiver exact?
1217 actual_receiver_is_exact = receiver_type->klass_is_exact();
1218 }
1219
1220 ciInstanceKlass* calling_klass = caller->holder();
1221 ciMethod* cha_monomorphic_target = callee->find_monomorphic_target(calling_klass, klass, actual_receiver, check_access);
1222
1223 if (cha_monomorphic_target != nullptr) {
1224 // Hardwiring a virtual.
1225 assert(!callee->can_be_statically_bound(), "should have been handled earlier");
1226 assert(!cha_monomorphic_target->is_abstract(), "");
1227 if (!cha_monomorphic_target->can_be_statically_bound(actual_receiver)) {
1228 // If we inlined because CHA revealed only a single target method,
1229 // then we are dependent on that target method not getting overridden
1230 // by dynamic class loading. Be sure to test the "static" receiver
1231 // dest_method here, as opposed to the actual receiver, which may
1232 // falsely lead us to believe that the receiver is final or private.
1233 dependencies()->assert_unique_concrete_method(actual_receiver, cha_monomorphic_target, holder, callee);
1234 }
1235 return cha_monomorphic_target;
1236 }
1237
1238 // If the type is exact, we can still bind the method w/o a vcall.
1239 // (This case comes after CHA so we can see how much extra work it does.)
1240 if (actual_receiver_is_exact) {
1241 // In case of evolution, there is a dependence on every inlined method, since each
1242 // such method can be changed when its class is redefined.
1243 ciMethod* exact_method = callee->resolve_invoke(calling_klass, actual_receiver);
1244 if (exact_method != nullptr) {
1245 return exact_method;
1246 }
1247 }
1248
1249 return nullptr;
1250 }