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