1 /*
2 * Copyright (c) 1997, 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/ciObjArrayKlass.hpp"
26 #include "ci/ciSignature.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "interpreter/linkResolver.hpp"
29 #include "memory/resourceArea.hpp"
30 #include "oops/method.hpp"
31 #include "opto/addnode.hpp"
32 #include "opto/c2compiler.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/convertnode.hpp"
35 #include "opto/idealGraphPrinter.hpp"
36 #include "opto/inlinetypenode.hpp"
37 #include "opto/locknode.hpp"
38 #include "opto/memnode.hpp"
39 #include "opto/opaquenode.hpp"
40 #include "opto/parse.hpp"
41 #include "opto/rootnode.hpp"
42 #include "opto/runtime.hpp"
43 #include "opto/type.hpp"
44 #include "runtime/arguments.hpp"
45 #include "runtime/handles.inline.hpp"
46 #include "runtime/safepointMechanism.hpp"
47 #include "runtime/sharedRuntime.hpp"
48 #include "utilities/bitMap.inline.hpp"
49 #include "utilities/copy.hpp"
50
51 // Static array so we can figure out which bytecodes stop us from compiling
52 // the most. Some of the non-static variables are needed in bytecodeInfo.cpp
53 // and eventually should be encapsulated in a proper class (gri 8/18/98).
54
55 #ifndef PRODUCT
56 uint nodes_created = 0;
57 uint methods_parsed = 0;
58 uint methods_seen = 0;
59 uint blocks_parsed = 0;
60 uint blocks_seen = 0;
61
62 uint explicit_null_checks_inserted = 0;
63 uint explicit_null_checks_elided = 0;
64 uint all_null_checks_found = 0;
65 uint implicit_null_checks = 0;
66
67 bool Parse::BytecodeParseHistogram::_initialized = false;
68 uint Parse::BytecodeParseHistogram::_bytecodes_parsed [Bytecodes::number_of_codes];
69 uint Parse::BytecodeParseHistogram::_nodes_constructed[Bytecodes::number_of_codes];
70 uint Parse::BytecodeParseHistogram::_nodes_transformed[Bytecodes::number_of_codes];
71 uint Parse::BytecodeParseHistogram::_new_values [Bytecodes::number_of_codes];
72
73 //------------------------------print_statistics-------------------------------
74 void Parse::print_statistics() {
75 tty->print_cr("--- Compiler Statistics ---");
76 tty->print("Methods seen: %u Methods parsed: %u", methods_seen, methods_parsed);
77 tty->print(" Nodes created: %u", nodes_created);
78 tty->cr();
79 if (methods_seen != methods_parsed) {
80 tty->print_cr("Reasons for parse failures (NOT cumulative):");
81 }
82 tty->print_cr("Blocks parsed: %u Blocks seen: %u", blocks_parsed, blocks_seen);
83
84 if (explicit_null_checks_inserted) {
85 tty->print_cr("%u original null checks - %u elided (%2u%%); optimizer leaves %u,",
86 explicit_null_checks_inserted, explicit_null_checks_elided,
87 (100*explicit_null_checks_elided)/explicit_null_checks_inserted,
88 all_null_checks_found);
89 }
90 if (all_null_checks_found) {
91 tty->print_cr("%u made implicit (%2u%%)", implicit_null_checks,
92 (100*implicit_null_checks)/all_null_checks_found);
93 }
94 if (SharedRuntime::_implicit_null_throws) {
95 tty->print_cr("%u implicit null exceptions at runtime",
96 SharedRuntime::_implicit_null_throws);
97 }
98
99 if (PrintParseStatistics && BytecodeParseHistogram::initialized()) {
100 BytecodeParseHistogram::print();
101 }
102 }
103 #endif
104
105 //------------------------------ON STACK REPLACEMENT---------------------------
106
107 // Construct a node which can be used to get incoming state for
108 // on stack replacement.
109 Node* Parse::fetch_interpreter_state(int index,
110 const Type* type,
111 Node* local_addrs) {
112 BasicType bt = type->basic_type();
113 if (type == TypePtr::NULL_PTR) {
114 // Ptr types are mixed together with T_ADDRESS but nullptr is
115 // really for T_OBJECT types so correct it.
116 bt = T_OBJECT;
117 }
118 Node *mem = memory(Compile::AliasIdxRaw);
119 Node *adr = basic_plus_adr(top(), local_addrs, -index*wordSize);
120 Node *ctl = control();
121
122 // Very similar to LoadNode::make, except we handle un-aligned longs and
123 // doubles on Sparc. Intel can handle them just fine directly.
124 Node *l = nullptr;
125 switch (bt) { // Signature is flattened
126 case T_INT: l = new LoadINode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInt::INT, MemNode::unordered); break;
127 case T_FLOAT: l = new LoadFNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::FLOAT, MemNode::unordered); break;
128 case T_ADDRESS: l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered); break;
129 case T_OBJECT: l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInstPtr::BOTTOM, MemNode::unordered); break;
130 case T_LONG:
131 case T_DOUBLE: {
132 // Since arguments are in reverse order, the argument address 'adr'
133 // refers to the back half of the long/double. Recompute adr.
134 adr = basic_plus_adr(top(), local_addrs, -(index+1)*wordSize);
135 if (Matcher::misaligned_doubles_ok) {
136 l = (bt == T_DOUBLE)
137 ? (Node*)new LoadDNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::DOUBLE, MemNode::unordered)
138 : (Node*)new LoadLNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeLong::LONG, MemNode::unordered);
139 } else {
140 l = (bt == T_DOUBLE)
141 ? (Node*)new LoadD_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered)
142 : (Node*)new LoadL_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered);
143 }
144 break;
145 }
146 default: ShouldNotReachHere();
147 }
148 return _gvn.transform(l);
149 }
150
151 // Helper routine to prevent the interpreter from handing
152 // unexpected typestate to an OSR method.
153 // The Node l is a value newly dug out of the interpreter frame.
154 // The type is the type predicted by ciTypeFlow. Note that it is
155 // not a general type, but can only come from Type::get_typeflow_type.
156 // The safepoint is a map which will feed an uncommon trap.
157 Node* Parse::check_interpreter_type(Node* l, const Type* type, const TypeKlassPtr* klass_type,
158 SafePointNode* &bad_type_exit, bool is_early_larval) {
159 const TypeOopPtr* tp = type->isa_oopptr();
160
161 // TypeFlow may assert null-ness if a type appears unloaded.
162 if (type == TypePtr::NULL_PTR ||
163 (tp != nullptr && !tp->is_loaded())) {
164 // Value must be null, not a real oop.
165 Node* chk = _gvn.transform( new CmpPNode(l, null()) );
166 Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
167 IfNode* iff = create_and_map_if(control(), tst, PROB_MAX, COUNT_UNKNOWN);
168 set_control(_gvn.transform( new IfTrueNode(iff) ));
169 Node* bad_type = _gvn.transform( new IfFalseNode(iff) );
170 bad_type_exit->control()->add_req(bad_type);
171 l = null();
172 }
173
174 // Typeflow can also cut off paths from the CFG, based on
175 // types which appear unloaded, or call sites which appear unlinked.
176 // When paths are cut off, values at later merge points can rise
177 // toward more specific classes. Make sure these specific classes
178 // are still in effect.
179 if (tp != nullptr && !tp->is_same_java_type_as(TypeInstPtr::BOTTOM)) {
180 // TypeFlow asserted a specific object type. Value must have that type.
181 Node* bad_type_ctrl = nullptr;
182 if (tp->is_inlinetypeptr() && !tp->maybe_null()) {
183 // Check inline types for null here to prevent checkcast from adding an
184 // exception state before the bytecode entry (use 'bad_type_ctrl' instead).
185 l = null_check_oop(l, &bad_type_ctrl);
186 bad_type_exit->control()->add_req(bad_type_ctrl);
187 }
188
189 l = gen_checkcast(l, makecon(klass_type), &bad_type_ctrl, false, is_early_larval);
190 bad_type_exit->control()->add_req(bad_type_ctrl);
191 }
192
193 assert(_gvn.type(l)->higher_equal(type), "must constrain OSR typestate");
194 return l;
195 }
196
197 // Helper routine which sets up elements of the initial parser map when
198 // performing a parse for on stack replacement. Add values into map.
199 // The only parameter contains the address of a interpreter arguments.
200 void Parse::load_interpreter_state(Node* osr_buf) {
201 int index;
202 int max_locals = jvms()->loc_size();
203 int max_stack = jvms()->stk_size();
204
205 // Mismatch between method and jvms can occur since map briefly held
206 // an OSR entry state (which takes up one RawPtr word).
207 assert(max_locals == method()->max_locals(), "sanity");
208 assert(max_stack >= method()->max_stack(), "sanity");
209 assert((int)jvms()->endoff() == TypeFunc::Parms + max_locals + max_stack, "sanity");
210 assert((int)jvms()->endoff() == (int)map()->req(), "sanity");
211
212 // Find the start block.
213 Block* osr_block = start_block();
214 assert(osr_block->start() == osr_bci(), "sanity");
215
216 // Set initial BCI.
217 set_parse_bci(osr_block->start());
218
219 // Set initial stack depth.
220 set_sp(osr_block->start_sp());
221
222 // Check bailouts. We currently do not perform on stack replacement
223 // of loops in catch blocks or loops which branch with a non-empty stack.
224 if (sp() != 0) {
225 C->record_method_not_compilable("OSR starts with non-empty stack");
226 return;
227 }
228 // Do not OSR inside finally clauses:
229 if (osr_block->has_trap_at(osr_block->start())) {
230 assert(false, "OSR starts with an immediate trap");
231 C->record_method_not_compilable("OSR starts with an immediate trap");
232 return;
233 }
234
235 // Commute monitors from interpreter frame to compiler frame.
236 assert(jvms()->monitor_depth() == 0, "should be no active locks at beginning of osr");
237 int mcnt = osr_block->flow()->monitor_count();
238 Node *monitors_addr = basic_plus_adr(top(), osr_buf, (max_locals+mcnt*2-1)*wordSize);
239 for (index = 0; index < mcnt; index++) {
240 // Make a BoxLockNode for the monitor.
241 BoxLockNode* osr_box = new BoxLockNode(next_monitor());
242 // Check for bailout after new BoxLockNode
243 if (failing()) { return; }
244
245 // This OSR locking region is unbalanced because it does not have Lock node:
246 // locking was done in Interpreter.
247 // This is similar to Coarsened case when Lock node is eliminated
248 // and as result the region is marked as Unbalanced.
249
250 // Emulate Coarsened state transition from Regular to Unbalanced.
251 osr_box->set_coarsened();
252 osr_box->set_unbalanced();
253
254 Node* box = _gvn.transform(osr_box);
255
256 // Displaced headers and locked objects are interleaved in the
257 // temp OSR buffer. We only copy the locked objects out here.
258 // Fetch the locked object from the OSR temp buffer and copy to our fastlock node.
259 Node* lock_object = fetch_interpreter_state(index*2, Type::get_const_basic_type(T_OBJECT), monitors_addr);
260 // Try and copy the displaced header to the BoxNode
261 Node* displaced_hdr = fetch_interpreter_state((index*2) + 1, Type::get_const_basic_type(T_ADDRESS), monitors_addr);
262
263 store_to_memory(control(), box, displaced_hdr, T_ADDRESS, MemNode::unordered);
264
265 // Build a bogus FastLockNode (no code will be generated) and push the
266 // monitor into our debug info.
267 const FastLockNode *flock = _gvn.transform(new FastLockNode( nullptr, lock_object, box ))->as_FastLock();
268 map()->push_monitor(flock);
269
270 // If the lock is our method synchronization lock, tuck it away in
271 // _sync_lock for return and rethrow exit paths.
272 if (index == 0 && method()->is_synchronized()) {
273 _synch_lock = flock;
274 }
275 }
276
277 // Use the raw liveness computation to make sure that unexpected
278 // values don't propagate into the OSR frame.
279 MethodLivenessResult live_locals = method()->liveness_at_bci(osr_bci());
280 if (!live_locals.is_valid()) {
281 // Degenerate or breakpointed method.
282 assert(false, "OSR in empty or breakpointed method");
283 C->record_method_not_compilable("OSR in empty or breakpointed method");
284 return;
285 }
286
287 // Extract the needed locals from the interpreter frame.
288 Node *locals_addr = basic_plus_adr(top(), osr_buf, (max_locals-1)*wordSize);
289
290 // find all the locals that the interpreter thinks contain live oops
291 const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci());
292 for (index = 0; index < max_locals; index++) {
293
294 if (!live_locals.at(index)) {
295 continue;
296 }
297
298 const Type *type = osr_block->local_type_at(index);
299
300 if (type->isa_oopptr() != nullptr) {
301
302 // 6403625: Verify that the interpreter oopMap thinks that the oop is live
303 // else we might load a stale oop if the MethodLiveness disagrees with the
304 // result of the interpreter. If the interpreter says it is dead we agree
305 // by making the value go to top.
306 //
307
308 if (!live_oops.at(index)) {
309 if (C->log() != nullptr) {
310 C->log()->elem("OSR_mismatch local_index='%d'",index);
311 }
312 set_local(index, null());
313 // and ignore it for the loads
314 continue;
315 }
316 }
317
318 // Filter out TOP, HALF, and BOTTOM. (Cf. ensure_phi.)
319 if (type == Type::TOP || type == Type::HALF) {
320 continue;
321 }
322 // If the type falls to bottom, then this must be a local that
323 // is mixing ints and oops or some such. Forcing it to top
324 // makes it go dead.
325 if (type == Type::BOTTOM) {
326 continue;
327 }
328 // Construct code to access the appropriate local.
329 Node* value = fetch_interpreter_state(index, type, locals_addr);
330 set_local(index, value);
331 }
332
333 // Extract the needed stack entries from the interpreter frame.
334 for (index = 0; index < sp(); index++) {
335 const Type *type = osr_block->stack_type_at(index);
336 if (type != Type::TOP) {
337 // Currently the compiler bails out when attempting to on stack replace
338 // at a bci with a non-empty stack. We should not reach here.
339 ShouldNotReachHere();
340 }
341 }
342
343 // End the OSR migration
344 make_runtime_call(RC_LEAF, OptoRuntime::osr_end_Type(),
345 CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
346 "OSR_migration_end", TypeRawPtr::BOTTOM,
347 osr_buf);
348
349 // Now that the interpreter state is loaded, make sure it will match
350 // at execution time what the compiler is expecting now:
351 SafePointNode* bad_type_exit = clone_map();
352 bad_type_exit->set_control(new RegionNode(1));
353
354 assert(osr_block->flow()->jsrs()->size() == 0, "should be no jsrs live at osr point");
355 for (index = 0; index < max_locals; index++) {
356 if (stopped()) break;
357 Node* l = local(index);
358 if (l->is_top()) continue; // nothing here
359 const Type *type = osr_block->local_type_at(index);
360 if (type->isa_oopptr() != nullptr) {
361 if (!live_oops.at(index)) {
362 // skip type check for dead oops
363 continue;
364 }
365 }
366 if (osr_block->flow()->local_type_at(index)->is_return_address()) {
367 // In our current system it's illegal for jsr addresses to be
368 // live into an OSR entry point because the compiler performs
369 // inlining of jsrs. ciTypeFlow has a bailout that detect this
370 // case and aborts the compile if addresses are live into an OSR
371 // entry point. Because of that we can assume that any address
372 // locals at the OSR entry point are dead. Method liveness
373 // isn't precise enough to figure out that they are dead in all
374 // cases so simply skip checking address locals all
375 // together. Any type check is guaranteed to fail since the
376 // interpreter type is the result of a load which might have any
377 // value and the expected type is a constant.
378 continue;
379 }
380 const TypeKlassPtr* klass_type = nullptr;
381 if (type->isa_oopptr()) {
382 klass_type = TypeKlassPtr::make(osr_block->flow()->local_type_at(index)->unwrap()->as_klass(), Type::ignore_interfaces);
383 klass_type = klass_type->try_improve();
384 }
385 bool is_early_larval = osr_block->flow()->local_type_at(index)->is_early_larval();
386 set_local(index, check_interpreter_type(l, type, klass_type, bad_type_exit, is_early_larval));
387 }
388
389 for (index = 0; index < sp(); index++) {
390 if (stopped()) break;
391 Node* l = stack(index);
392 if (l->is_top()) continue; // nothing here
393 const Type* type = osr_block->stack_type_at(index);
394 const TypeKlassPtr* klass_type = nullptr;
395 if (type->isa_oopptr()) {
396 klass_type = TypeKlassPtr::make(osr_block->flow()->stack_type_at(index)->unwrap()->as_klass(), Type::ignore_interfaces);
397 klass_type = klass_type->try_improve();
398 }
399 bool is_early_larval = osr_block->flow()->stack_type_at(index)->is_early_larval();
400 set_stack(index, check_interpreter_type(l, type, klass_type, bad_type_exit, is_early_larval));
401 }
402
403 if (bad_type_exit->control()->req() > 1) {
404 // Build an uncommon trap here, if any inputs can be unexpected.
405 bad_type_exit->set_control(_gvn.transform( bad_type_exit->control() ));
406 record_for_igvn(bad_type_exit->control());
407 SafePointNode* types_are_good = map();
408 set_map(bad_type_exit);
409 // The unexpected type happens because a new edge is active
410 // in the CFG, which typeflow had previously ignored.
411 // E.g., Object x = coldAtFirst() && notReached()? "str": new Integer(123).
412 // This x will be typed as Integer if notReached is not yet linked.
413 // It could also happen due to a problem in ciTypeFlow analysis.
414 uncommon_trap(Deoptimization::Reason_constraint,
415 Deoptimization::Action_reinterpret);
416 set_map(types_are_good);
417 }
418 }
419
420 //------------------------------Parse------------------------------------------
421 // Main parser constructor.
422 Parse::Parse(JVMState* caller, ciMethod* parse_method, float expected_uses)
423 : _exits(caller)
424 {
425 // Init some variables
426 _caller = caller;
427 _method = parse_method;
428 _expected_uses = expected_uses;
429 _depth = 1 + (caller->has_method() ? caller->depth() : 0);
430 _wrote_final = false;
431 _wrote_volatile = false;
432 _wrote_stable = false;
433 _wrote_fields = false;
434 _alloc_with_final_or_stable = nullptr;
435 _block = nullptr;
436 _first_return = true;
437 _replaced_nodes_for_exceptions = false;
438 _new_idx = C->unique();
439 DEBUG_ONLY(_entry_bci = UnknownBci);
440 DEBUG_ONLY(_block_count = -1);
441 DEBUG_ONLY(_blocks = (Block*)-1);
442 #ifndef PRODUCT
443 if (PrintCompilation || PrintOpto) {
444 // Make sure I have an inline tree, so I can print messages about it.
445 InlineTree::find_subtree_from_root(C->ilt(), caller, parse_method);
446 }
447 _max_switch_depth = 0;
448 _est_switch_depth = 0;
449 #endif
450
451 if (parse_method->has_reserved_stack_access()) {
452 C->set_has_reserved_stack_access(true);
453 }
454
455 if (parse_method->is_synchronized() || parse_method->has_monitor_bytecodes()) {
456 C->set_has_monitors(true);
457 }
458
459 if (parse_method->is_scoped()) {
460 C->set_has_scoped_access(true);
461 }
462
463 _iter.reset_to_method(method());
464 C->set_has_loops(C->has_loops() || method()->has_loops());
465
466 if (_expected_uses <= 0) {
467 _prof_factor = 1;
468 } else {
469 float prof_total = parse_method->interpreter_invocation_count();
470 if (prof_total <= _expected_uses) {
471 _prof_factor = 1;
472 } else {
473 _prof_factor = _expected_uses / prof_total;
474 }
475 }
476
477 CompileLog* log = C->log();
478 if (log != nullptr) {
479 log->begin_head("parse method='%d' uses='%f'",
480 log->identify(parse_method), expected_uses);
481 if (depth() == 1 && C->is_osr_compilation()) {
482 log->print(" osr_bci='%d'", C->entry_bci());
483 }
484 log->stamp();
485 log->end_head();
486 }
487
488 // Accumulate deoptimization counts.
489 // (The range_check and store_check counts are checked elsewhere.)
490 ciMethodData* md = method()->method_data();
491 for (uint reason = 0; reason < md->trap_reason_limit(); reason++) {
492 uint md_count = md->trap_count(reason);
493 if (md_count != 0) {
494 if (md_count >= md->trap_count_limit()) {
495 md_count = md->trap_count_limit() + md->overflow_trap_count();
496 }
497 uint total_count = C->trap_count(reason);
498 uint old_count = total_count;
499 total_count += md_count;
500 // Saturate the add if it overflows.
501 if (total_count < old_count || total_count < md_count)
502 total_count = (uint)-1;
503 C->set_trap_count(reason, total_count);
504 if (log != nullptr)
505 log->elem("observe trap='%s' count='%d' total='%d'",
506 Deoptimization::trap_reason_name(reason),
507 md_count, total_count);
508 }
509 }
510 // Accumulate total sum of decompilations, also.
511 C->set_decompile_count(C->decompile_count() + md->decompile_count());
512
513 if (log != nullptr && method()->has_exception_handlers()) {
514 log->elem("observe that='has_exception_handlers'");
515 }
516
517 assert(InlineTree::check_can_parse(method()) == nullptr, "Can not parse this method, cutout earlier");
518 assert(method()->has_balanced_monitors(), "Can not parse unbalanced monitors, cutout earlier");
519
520 // Always register dependence if JVMTI is enabled, because
521 // either breakpoint setting or hotswapping of methods may
522 // cause deoptimization.
523 if (C->env()->jvmti_can_hotswap_or_post_breakpoint()) {
524 C->dependencies()->assert_evol_method(method());
525 }
526
527 NOT_PRODUCT(methods_seen++);
528
529 // Do some special top-level things.
530 if (depth() == 1 && C->is_osr_compilation()) {
531 _tf = C->tf(); // the OSR entry type is different
532 _entry_bci = C->entry_bci();
533 _flow = method()->get_osr_flow_analysis(osr_bci());
534 } else {
535 _tf = TypeFunc::make(method());
536 _entry_bci = InvocationEntryBci;
537 _flow = method()->get_flow_analysis();
538 }
539
540 if (_flow->failing()) {
541 // TODO Adding a trap due to an unloaded return type in ciTypeFlow::StateVector::do_invoke
542 // can lead to this. Re-enable once 8284443 is fixed.
543 //assert(false, "type flow analysis failed during parsing");
544 C->record_method_not_compilable(_flow->failure_reason());
545 #ifndef PRODUCT
546 if (PrintOpto && (Verbose || WizardMode)) {
547 if (is_osr_parse()) {
548 tty->print_cr("OSR @%d type flow bailout: %s", _entry_bci, _flow->failure_reason());
549 } else {
550 tty->print_cr("type flow bailout: %s", _flow->failure_reason());
551 }
552 if (Verbose) {
553 method()->print();
554 method()->print_codes();
555 _flow->print();
556 }
557 }
558 #endif
559 }
560
561 #ifdef ASSERT
562 if (depth() == 1) {
563 assert(C->is_osr_compilation() == this->is_osr_parse(), "OSR in sync");
564 } else {
565 assert(!this->is_osr_parse(), "no recursive OSR");
566 }
567 #endif
568
569 #ifndef PRODUCT
570 if (_flow->has_irreducible_entry()) {
571 C->set_parsed_irreducible_loop(true);
572 }
573
574 methods_parsed++;
575 // add method size here to guarantee that inlined methods are added too
576 if (CITime)
577 _total_bytes_compiled += method()->code_size();
578
579 show_parse_info();
580 #endif
581
582 if (failing()) {
583 if (log) log->done("parse");
584 return;
585 }
586
587 gvn().transform(top());
588
589 // Import the results of the ciTypeFlow.
590 init_blocks();
591
592 // Merge point for all normal exits
593 build_exits();
594
595 // Setup the initial JVM state map.
596 SafePointNode* entry_map = create_entry_map();
597
598 // Check for bailouts during map initialization
599 if (failing() || entry_map == nullptr) {
600 if (log) log->done("parse");
601 return;
602 }
603
604 Node_Notes* caller_nn = C->default_node_notes();
605 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
606 if (DebugInlinedCalls || depth() == 1) {
607 C->set_default_node_notes(make_node_notes(caller_nn));
608 }
609
610 if (is_osr_parse()) {
611 Node* osr_buf = entry_map->in(TypeFunc::Parms+0);
612 entry_map->set_req(TypeFunc::Parms+0, top());
613 set_map(entry_map);
614 load_interpreter_state(osr_buf);
615 } else {
616 set_map(entry_map);
617 do_method_entry();
618 }
619
620 if (depth() == 1 && !failing()) {
621 if (C->clinit_barrier_on_entry()) {
622 // Add check to deoptimize the nmethod once the holder class is fully initialized
623 clinit_deopt();
624 }
625 }
626
627 // Check for bailouts during method entry.
628 if (failing()) {
629 if (log) log->done("parse");
630 C->set_default_node_notes(caller_nn);
631 return;
632 }
633
634 entry_map = map(); // capture any changes performed by method setup code
635 assert(jvms()->endoff() == map()->req(), "map matches JVMS layout");
636
637 // We begin parsing as if we have just encountered a jump to the
638 // method entry.
639 Block* entry_block = start_block();
640 assert(entry_block->start() == (is_osr_parse() ? osr_bci() : 0), "");
641 set_map_clone(entry_map);
642 merge_common(entry_block, entry_block->next_path_num());
643
644 #ifndef PRODUCT
645 BytecodeParseHistogram *parse_histogram_obj = new (C->env()->arena()) BytecodeParseHistogram(this, C);
646 set_parse_histogram( parse_histogram_obj );
647 #endif
648
649 // Parse all the basic blocks.
650 do_all_blocks();
651
652 // Check for bailouts during conversion to graph
653 if (failing()) {
654 if (log) log->done("parse");
655 return;
656 }
657
658 // Fix up all exiting control flow.
659 set_map(entry_map);
660 do_exits();
661
662 // Only reset this now, to make sure that debug information emitted
663 // for exiting control flow still refers to the inlined method.
664 C->set_default_node_notes(caller_nn);
665
666 if (log) log->done("parse nodes='%d' live='%d' memory='%zu'",
667 C->unique(), C->live_nodes(), C->node_arena()->used());
668 }
669
670 //---------------------------do_all_blocks-------------------------------------
671 void Parse::do_all_blocks() {
672 bool has_irreducible = flow()->has_irreducible_entry();
673
674 // Walk over all blocks in Reverse Post-Order.
675 while (true) {
676 bool progress = false;
677 for (int rpo = 0; rpo < block_count(); rpo++) {
678 Block* block = rpo_at(rpo);
679
680 if (block->is_parsed()) continue;
681
682 if (!block->is_merged()) {
683 // Dead block, no state reaches this block
684 continue;
685 }
686
687 // Prepare to parse this block.
688 load_state_from(block);
689
690 if (stopped()) {
691 // Block is dead.
692 continue;
693 }
694
695 NOT_PRODUCT(blocks_parsed++);
696
697 progress = true;
698 if (block->is_loop_head() || block->is_handler() || (has_irreducible && !block->is_ready())) {
699 // Not all preds have been parsed. We must build phis everywhere.
700 // (Note that dead locals do not get phis built, ever.)
701 ensure_phis_everywhere();
702
703 if (block->is_SEL_head()) {
704 // Add predicate to single entry (not irreducible) loop head.
705 assert(!block->has_merged_backedge(), "only entry paths should be merged for now");
706 // Predicates may have been added after a dominating if
707 if (!block->has_predicates()) {
708 // Need correct bci for predicate.
709 // It is fine to set it here since do_one_block() will set it anyway.
710 set_parse_bci(block->start());
711 add_parse_predicates();
712 }
713 // Add new region for back branches.
714 int edges = block->pred_count() - block->preds_parsed() + 1; // +1 for original region
715 RegionNode *r = new RegionNode(edges+1);
716 _gvn.set_type(r, Type::CONTROL);
717 record_for_igvn(r);
718 r->init_req(edges, control());
719 set_control(r);
720 block->copy_irreducible_status_to(r, jvms());
721 // Add new phis.
722 ensure_phis_everywhere();
723 }
724
725 // Leave behind an undisturbed copy of the map, for future merges.
726 set_map(clone_map());
727 }
728
729 if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) {
730 // In the absence of irreducible loops, the Region and Phis
731 // associated with a merge that doesn't involve a backedge can
732 // be simplified now since the RPO parsing order guarantees
733 // that any path which was supposed to reach here has already
734 // been parsed or must be dead.
735 Node* c = control();
736 Node* result = _gvn.transform(control());
737 if (c != result && TraceOptoParse) {
738 tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx);
739 }
740 if (result != top()) {
741 record_for_igvn(result);
742 }
743 }
744
745 // Parse the block.
746 do_one_block();
747
748 // Check for bailouts.
749 if (failing()) return;
750 }
751
752 // with irreducible loops multiple passes might be necessary to parse everything
753 if (!has_irreducible || !progress) {
754 break;
755 }
756 }
757
758 #ifndef PRODUCT
759 blocks_seen += block_count();
760
761 // Make sure there are no half-processed blocks remaining.
762 // Every remaining unprocessed block is dead and may be ignored now.
763 for (int rpo = 0; rpo < block_count(); rpo++) {
764 Block* block = rpo_at(rpo);
765 if (!block->is_parsed()) {
766 if (TraceOptoParse) {
767 tty->print_cr("Skipped dead block %d at bci:%d", rpo, block->start());
768 }
769 assert(!block->is_merged(), "no half-processed blocks");
770 }
771 }
772 #endif
773 }
774
775 static Node* mask_int_value(Node* v, BasicType bt, PhaseGVN* gvn) {
776 switch (bt) {
777 case T_BYTE:
778 v = gvn->transform(new LShiftINode(v, gvn->intcon(24)));
779 v = gvn->transform(new RShiftINode(v, gvn->intcon(24)));
780 break;
781 case T_SHORT:
782 v = gvn->transform(new LShiftINode(v, gvn->intcon(16)));
783 v = gvn->transform(new RShiftINode(v, gvn->intcon(16)));
784 break;
785 case T_CHAR:
786 v = gvn->transform(new AndINode(v, gvn->intcon(0xFFFF)));
787 break;
788 case T_BOOLEAN:
789 v = gvn->transform(new AndINode(v, gvn->intcon(0x1)));
790 break;
791 default:
792 break;
793 }
794 return v;
795 }
796
797 //-------------------------------build_exits----------------------------------
798 // Build normal and exceptional exit merge points.
799 void Parse::build_exits() {
800 // make a clone of caller to prevent sharing of side-effects
801 _exits.set_map(_exits.clone_map());
802 _exits.clean_stack(_exits.sp());
803 _exits.sync_jvms();
804
805 RegionNode* region = new RegionNode(1);
806 record_for_igvn(region);
807 gvn().set_type_bottom(region);
808 _exits.set_control(region);
809
810 // Note: iophi and memphi are not transformed until do_exits.
811 Node* iophi = new PhiNode(region, Type::ABIO);
812 Node* memphi = new PhiNode(region, Type::MEMORY, TypePtr::BOTTOM);
813 gvn().set_type_bottom(iophi);
814 gvn().set_type_bottom(memphi);
815 _exits.set_i_o(iophi);
816 _exits.set_all_memory(memphi);
817
818 // Add a return value to the exit state. (Do not push it yet.)
819 if (tf()->range_sig()->cnt() > TypeFunc::Parms) {
820 const Type* ret_type = tf()->range_sig()->field_at(TypeFunc::Parms);
821 if (ret_type->isa_int()) {
822 BasicType ret_bt = method()->return_type()->basic_type();
823 if (ret_bt == T_BOOLEAN ||
824 ret_bt == T_CHAR ||
825 ret_bt == T_BYTE ||
826 ret_bt == T_SHORT) {
827 ret_type = TypeInt::INT;
828 }
829 }
830
831 // Don't "bind" an unloaded return klass to the ret_phi. If the klass
832 // becomes loaded during the subsequent parsing, the loaded and unloaded
833 // types will not join when we transform and push in do_exits().
834 const TypeOopPtr* ret_oop_type = ret_type->isa_oopptr();
835 if (ret_oop_type && !ret_oop_type->is_loaded()) {
836 ret_type = TypeOopPtr::BOTTOM;
837 }
838 int ret_size = type2size[ret_type->basic_type()];
839 Node* ret_phi = new PhiNode(region, ret_type);
840 gvn().set_type_bottom(ret_phi);
841 _exits.ensure_stack(ret_size);
842 assert((int)(tf()->range_sig()->cnt() - TypeFunc::Parms) == ret_size, "good tf range");
843 assert(method()->return_type()->size() == ret_size, "tf agrees w/ method");
844 _exits.set_argument(0, ret_phi); // here is where the parser finds it
845 // Note: ret_phi is not yet pushed, until do_exits.
846 }
847 }
848
849 //----------------------------build_start_state-------------------------------
850 // Construct a state which contains only the incoming arguments from an
851 // unknown caller. The method & bci will be null & InvocationEntryBci.
852 JVMState* Compile::build_start_state(StartNode* start, const TypeFunc* tf) {
853 int arg_size = tf->domain_sig()->cnt();
854 int max_size = MAX2(arg_size, (int)tf->range_cc()->cnt());
855 JVMState* jvms = new (this) JVMState(max_size - TypeFunc::Parms);
856 SafePointNode* map = new SafePointNode(max_size, jvms);
857 jvms->set_map(map);
858 record_for_igvn(map);
859 assert(arg_size == TypeFunc::Parms + (is_osr_compilation() ? 1 : method()->arg_size()), "correct arg_size");
860 Node_Notes* old_nn = default_node_notes();
861 if (old_nn != nullptr && has_method()) {
862 Node_Notes* entry_nn = old_nn->clone(this);
863 JVMState* entry_jvms = new(this) JVMState(method(), old_nn->jvms());
864 entry_jvms->set_offsets(0);
865 entry_jvms->set_bci(entry_bci());
866 entry_nn->set_jvms(entry_jvms);
867 set_default_node_notes(entry_nn);
868 }
869 PhaseGVN& gvn = *initial_gvn();
870 uint i = 0;
871 int arg_num = 0;
872 for (uint j = 0; i < (uint)arg_size; i++) {
873 const Type* t = tf->domain_sig()->field_at(i);
874 Node* parm = nullptr;
875 if (t->is_inlinetypeptr() && method()->is_scalarized_arg(arg_num)) {
876 // Inline type arguments are not passed by reference: we get an argument per
877 // field of the inline type. Build InlineTypeNodes from the inline type arguments.
878 GraphKit kit(jvms, &gvn);
879 kit.set_control(map->control());
880 Node* old_mem = map->memory();
881 // Use immutable memory for inline type loads and restore it below
882 kit.set_all_memory(C->immutable_memory());
883 parm = InlineTypeNode::make_from_multi(&kit, start, t->inline_klass(), j, /* in= */ true, /* null_free= */ !t->maybe_null());
884 map->set_control(kit.control());
885 map->set_memory(old_mem);
886 } else {
887 parm = gvn.transform(new ParmNode(start, j++));
888 }
889 map->init_req(i, parm);
890 // Record all these guys for later GVN.
891 record_for_igvn(parm);
892 if (i >= TypeFunc::Parms && t != Type::HALF) {
893 arg_num++;
894 }
895 }
896 for (; i < map->req(); i++) {
897 map->init_req(i, top());
898 }
899 assert(jvms->argoff() == TypeFunc::Parms, "parser gets arguments here");
900 set_default_node_notes(old_nn);
901 return jvms;
902 }
903
904 //-----------------------------make_node_notes---------------------------------
905 Node_Notes* Parse::make_node_notes(Node_Notes* caller_nn) {
906 if (caller_nn == nullptr) return nullptr;
907 Node_Notes* nn = caller_nn->clone(C);
908 JVMState* caller_jvms = nn->jvms();
909 JVMState* jvms = new (C) JVMState(method(), caller_jvms);
910 jvms->set_offsets(0);
911 jvms->set_bci(_entry_bci);
912 nn->set_jvms(jvms);
913 return nn;
914 }
915
916
917 //--------------------------return_values--------------------------------------
918 void Compile::return_values(JVMState* jvms) {
919 GraphKit kit(jvms);
920 Node* ret = new ReturnNode(TypeFunc::Parms,
921 kit.control(),
922 kit.i_o(),
923 kit.reset_memory(),
924 kit.frameptr(),
925 kit.returnadr());
926 // Add zero or 1 return values
927 int ret_size = tf()->range_sig()->cnt() - TypeFunc::Parms;
928 if (ret_size > 0) {
929 kit.inc_sp(-ret_size); // pop the return value(s)
930 kit.sync_jvms();
931 Node* res = kit.argument(0);
932 if (tf()->returns_inline_type_as_fields()) {
933 // Multiple return values (inline type fields): add as many edges
934 // to the Return node as returned values.
935 InlineTypeNode* vt = res->as_InlineType();
936 ret->add_req_batch(nullptr, tf()->range_cc()->cnt() - TypeFunc::Parms);
937 if (vt->is_allocated(&kit.gvn()) && !StressCallingConvention) {
938 ret->init_req(TypeFunc::Parms, vt);
939 } else {
940 // Return the tagged klass pointer to signal scalarization to the caller
941 Node* tagged_klass = vt->tagged_klass(kit.gvn());
942 // Return null if the inline type is null (null marker field is not set)
943 Node* conv = kit.gvn().transform(new ConvI2LNode(vt->get_null_marker()));
944 Node* shl = kit.gvn().transform(new LShiftLNode(conv, kit.intcon(63)));
945 Node* shr = kit.gvn().transform(new RShiftLNode(shl, kit.intcon(63)));
946 tagged_klass = kit.gvn().transform(new AndLNode(tagged_klass, shr));
947 ret->init_req(TypeFunc::Parms, tagged_klass);
948 }
949 uint idx = TypeFunc::Parms + 1;
950 vt->pass_fields(&kit, ret, idx, false, false);
951 } else {
952 ret->add_req(res);
953 // Note: The second dummy edge is not needed by a ReturnNode.
954 }
955 }
956 // bind it to root
957 root()->add_req(ret);
958 record_for_igvn(ret);
959 initial_gvn()->transform(ret);
960 }
961
962 //------------------------rethrow_exceptions-----------------------------------
963 // Bind all exception states in the list into a single RethrowNode.
964 void Compile::rethrow_exceptions(JVMState* jvms) {
965 GraphKit kit(jvms);
966 if (!kit.has_exceptions()) return; // nothing to generate
967 // Load my combined exception state into the kit, with all phis transformed:
968 SafePointNode* ex_map = kit.combine_and_pop_all_exception_states();
969 Node* ex_oop = kit.use_exception_state(ex_map);
970 RethrowNode* exit = new RethrowNode(kit.control(),
971 kit.i_o(), kit.reset_memory(),
972 kit.frameptr(), kit.returnadr(),
973 // like a return but with exception input
974 ex_oop);
975 // bind to root
976 root()->add_req(exit);
977 record_for_igvn(exit);
978 initial_gvn()->transform(exit);
979 }
980
981 //---------------------------do_exceptions-------------------------------------
982 // Process exceptions arising from the current bytecode.
983 // Send caught exceptions to the proper handler within this method.
984 // Unhandled exceptions feed into _exit.
985 void Parse::do_exceptions() {
986 if (!has_exceptions()) return;
987
988 if (failing()) {
989 // Pop them all off and throw them away.
990 while (pop_exception_state() != nullptr) ;
991 return;
992 }
993
994 PreserveJVMState pjvms(this, false);
995
996 SafePointNode* ex_map;
997 while ((ex_map = pop_exception_state()) != nullptr) {
998 if (!method()->has_exception_handlers()) {
999 // Common case: Transfer control outward.
1000 // Doing it this early allows the exceptions to common up
1001 // even between adjacent method calls.
1002 throw_to_exit(ex_map);
1003 } else {
1004 // Have to look at the exception first.
1005 assert(stopped(), "catch_inline_exceptions trashes the map");
1006 catch_inline_exceptions(ex_map);
1007 stop_and_kill_map(); // we used up this exception state; kill it
1008 }
1009 }
1010
1011 // We now return to our regularly scheduled program:
1012 }
1013
1014 //---------------------------throw_to_exit-------------------------------------
1015 // Merge the given map into an exception exit from this method.
1016 // The exception exit will handle any unlocking of receiver.
1017 // The ex_oop must be saved within the ex_map, unlike merge_exception.
1018 void Parse::throw_to_exit(SafePointNode* ex_map) {
1019 // Pop the JVMS to (a copy of) the caller.
1020 GraphKit caller;
1021 caller.set_map_clone(_caller->map());
1022 caller.set_bci(_caller->bci());
1023 caller.set_sp(_caller->sp());
1024 // Copy out the standard machine state:
1025 for (uint i = 0; i < TypeFunc::Parms; i++) {
1026 caller.map()->set_req(i, ex_map->in(i));
1027 }
1028 if (ex_map->has_replaced_nodes()) {
1029 _replaced_nodes_for_exceptions = true;
1030 }
1031 caller.map()->transfer_replaced_nodes_from(ex_map, _new_idx);
1032 // ...and the exception:
1033 Node* ex_oop = saved_ex_oop(ex_map);
1034 SafePointNode* caller_ex_map = caller.make_exception_state(ex_oop);
1035 // Finally, collect the new exception state in my exits:
1036 _exits.add_exception_state(caller_ex_map);
1037 }
1038
1039 //------------------------------do_exits---------------------------------------
1040 void Parse::do_exits() {
1041 set_parse_bci(InvocationEntryBci);
1042
1043 // Now peephole on the return bits
1044 Node* region = _exits.control();
1045 _exits.set_control(gvn().transform(region));
1046
1047 Node* iophi = _exits.i_o();
1048 _exits.set_i_o(gvn().transform(iophi));
1049
1050 // Figure out if we need to emit the trailing barrier. The barrier is only
1051 // needed in the constructors, and only in three cases:
1052 //
1053 // 1. The constructor wrote a final or a @Stable field. All these
1054 // initializations must be ordered before any code after the constructor
1055 // publishes the reference to the newly constructed object. Rather
1056 // than wait for the publication, we simply block the writes here.
1057 // Rather than put a barrier on only those writes which are required
1058 // to complete, we force all writes to complete.
1059 //
1060 // 2. Experimental VM option is used to force the barrier if any field
1061 // was written out in the constructor.
1062 //
1063 // 3. On processors which are not CPU_MULTI_COPY_ATOMIC (e.g. PPC64),
1064 // support_IRIW_for_not_multiple_copy_atomic_cpu selects that
1065 // MemBarVolatile is used before volatile load instead of after volatile
1066 // store, so there's no barrier after the store.
1067 // We want to guarantee the same behavior as on platforms with total store
1068 // order, although this is not required by the Java memory model.
1069 // In this case, we want to enforce visibility of volatile field
1070 // initializations which are performed in constructors.
1071 // So as with finals, we add a barrier here.
1072 //
1073 // "All bets are off" unless the first publication occurs after a
1074 // normal return from the constructor. We do not attempt to detect
1075 // such unusual early publications. But no barrier is needed on
1076 // exceptional returns, since they cannot publish normally.
1077 //
1078 if ((method()->is_object_constructor() || method()->is_class_initializer()) &&
1079 (wrote_final() || wrote_stable() ||
1080 (AlwaysSafeConstructors && wrote_fields()) ||
1081 (support_IRIW_for_not_multiple_copy_atomic_cpu && wrote_volatile()))) {
1082 Node* recorded_alloc = alloc_with_final_or_stable();
1083 _exits.insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease,
1084 recorded_alloc);
1085
1086 // If Memory barrier is created for final fields write
1087 // and allocation node does not escape the initialize method,
1088 // then barrier introduced by allocation node can be removed.
1089 if (DoEscapeAnalysis && (recorded_alloc != nullptr)) {
1090 AllocateNode* alloc = AllocateNode::Ideal_allocation(recorded_alloc);
1091 alloc->compute_MemBar_redundancy(method());
1092 }
1093 if (PrintOpto && (Verbose || WizardMode)) {
1094 method()->print_name();
1095 tty->print_cr(" writes finals/@Stable and needs a memory barrier");
1096 }
1097 }
1098
1099 for (MergeMemStream mms(_exits.merged_memory()); mms.next_non_empty(); ) {
1100 // transform each slice of the original memphi:
1101 mms.set_memory(_gvn.transform(mms.memory()));
1102 }
1103 // Clean up input MergeMems created by transforming the slices
1104 _gvn.transform(_exits.merged_memory());
1105
1106 if (tf()->range_sig()->cnt() > TypeFunc::Parms) {
1107 const Type* ret_type = tf()->range_sig()->field_at(TypeFunc::Parms);
1108 Node* ret_phi = _gvn.transform( _exits.argument(0) );
1109 if (!_exits.control()->is_top() && _gvn.type(ret_phi)->empty()) {
1110 // If the type we set for the ret_phi in build_exits() is too optimistic and
1111 // the ret_phi is top now, there's an extremely small chance that it may be due to class
1112 // loading. It could also be due to an error, so mark this method as not compilable because
1113 // otherwise this could lead to an infinite compile loop.
1114 // In any case, this code path is rarely (and never in my testing) reached.
1115 C->record_method_not_compilable("Can't determine return type.");
1116 return;
1117 }
1118 if (ret_type->isa_int()) {
1119 BasicType ret_bt = method()->return_type()->basic_type();
1120 ret_phi = mask_int_value(ret_phi, ret_bt, &_gvn);
1121 }
1122 _exits.push_node(ret_type->basic_type(), ret_phi);
1123 }
1124
1125 // Note: Logic for creating and optimizing the ReturnNode is in Compile.
1126
1127 // Unlock along the exceptional paths.
1128 // This is done late so that we can common up equivalent exceptions
1129 // (e.g., null checks) arising from multiple points within this method.
1130 // See GraphKit::add_exception_state, which performs the commoning.
1131 bool do_synch = method()->is_synchronized();
1132
1133 // record exit from a method if compiled while Dtrace is turned on.
1134 if (do_synch || C->env()->dtrace_method_probes() || _replaced_nodes_for_exceptions) {
1135 // First move the exception list out of _exits:
1136 GraphKit kit(_exits.transfer_exceptions_into_jvms());
1137 SafePointNode* normal_map = kit.map(); // keep this guy safe
1138 // Now re-collect the exceptions into _exits:
1139 SafePointNode* ex_map;
1140 while ((ex_map = kit.pop_exception_state()) != nullptr) {
1141 Node* ex_oop = kit.use_exception_state(ex_map);
1142 // Force the exiting JVM state to have this method at InvocationEntryBci.
1143 // The exiting JVM state is otherwise a copy of the calling JVMS.
1144 JVMState* caller = kit.jvms();
1145 JVMState* ex_jvms = caller->clone_shallow(C);
1146 ex_jvms->bind_map(kit.clone_map());
1147 ex_jvms->set_bci( InvocationEntryBci);
1148 kit.set_jvms(ex_jvms);
1149 if (do_synch) {
1150 // Add on the synchronized-method box/object combo
1151 kit.map()->push_monitor(_synch_lock);
1152 // Unlock!
1153 kit.shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
1154 }
1155 if (C->env()->dtrace_method_probes()) {
1156 kit.make_dtrace_method_exit(method());
1157 }
1158 if (_replaced_nodes_for_exceptions) {
1159 kit.map()->apply_replaced_nodes(_new_idx);
1160 }
1161 // Done with exception-path processing.
1162 ex_map = kit.make_exception_state(ex_oop);
1163 assert(ex_jvms->same_calls_as(ex_map->jvms()), "sanity");
1164 // Pop the last vestige of this method:
1165 caller->clone_shallow(C)->bind_map(ex_map);
1166 _exits.push_exception_state(ex_map);
1167 }
1168 assert(_exits.map() == normal_map, "keep the same return state");
1169 }
1170
1171 {
1172 // Capture very early exceptions (receiver null checks) from caller JVMS
1173 GraphKit caller(_caller);
1174 SafePointNode* ex_map;
1175 while ((ex_map = caller.pop_exception_state()) != nullptr) {
1176 _exits.add_exception_state(ex_map);
1177 }
1178 }
1179 _exits.map()->apply_replaced_nodes(_new_idx);
1180 }
1181
1182 //-----------------------------create_entry_map-------------------------------
1183 // Initialize our parser map to contain the types at method entry.
1184 // For OSR, the map contains a single RawPtr parameter.
1185 // Initial monitor locking for sync. methods is performed by do_method_entry.
1186 SafePointNode* Parse::create_entry_map() {
1187 // Check for really stupid bail-out cases.
1188 uint len = TypeFunc::Parms + method()->max_locals() + method()->max_stack();
1189 if (len >= 32760) {
1190 // Bailout expected, this is a very rare edge case.
1191 C->record_method_not_compilable("too many local variables");
1192 return nullptr;
1193 }
1194
1195 // clear current replaced nodes that are of no use from here on (map was cloned in build_exits).
1196 _caller->map()->delete_replaced_nodes();
1197
1198 // If this is an inlined method, we may have to do a receiver null check.
1199 if (_caller->has_method() && is_normal_parse() && !method()->is_static()) {
1200 GraphKit kit(_caller);
1201 Node* receiver = kit.argument(0);
1202 Node* null_free = kit.null_check_receiver_before_call(method());
1203 _caller = kit.transfer_exceptions_into_jvms();
1204
1205 if (kit.stopped()) {
1206 _exits.add_exception_states_from(_caller);
1207 _exits.set_jvms(_caller);
1208 return nullptr;
1209 }
1210 }
1211
1212 assert(method() != nullptr, "parser must have a method");
1213
1214 // Create an initial safepoint to hold JVM state during parsing
1215 JVMState* jvms = new (C) JVMState(method(), _caller->has_method() ? _caller : nullptr);
1216 set_map(new SafePointNode(len, jvms));
1217
1218 // Capture receiver info for compiled lambda forms.
1219 if (method()->is_compiled_lambda_form()) {
1220 ciInstance* recv_info = _caller->compute_receiver_info(method());
1221 jvms->set_receiver_info(recv_info);
1222 }
1223
1224 jvms->set_map(map());
1225 record_for_igvn(map());
1226 assert(jvms->endoff() == len, "correct jvms sizing");
1227
1228 SafePointNode* inmap = _caller->map();
1229 assert(inmap != nullptr, "must have inmap");
1230 // In case of null check on receiver above
1231 map()->transfer_replaced_nodes_from(inmap, _new_idx);
1232
1233 uint i;
1234
1235 // Pass thru the predefined input parameters.
1236 for (i = 0; i < TypeFunc::Parms; i++) {
1237 map()->init_req(i, inmap->in(i));
1238 }
1239
1240 if (depth() == 1) {
1241 assert(map()->memory()->Opcode() == Op_Parm, "");
1242 // Insert the memory aliasing node
1243 set_all_memory(reset_memory());
1244 }
1245 assert(merged_memory(), "");
1246
1247 // Now add the locals which are initially bound to arguments:
1248 uint arg_size = tf()->domain_sig()->cnt();
1249 ensure_stack(arg_size - TypeFunc::Parms); // OSR methods have funny args
1250 for (i = TypeFunc::Parms; i < arg_size; i++) {
1251 map()->init_req(i, inmap->argument(_caller, i - TypeFunc::Parms));
1252 }
1253
1254 // Clear out the rest of the map (locals and stack)
1255 for (i = arg_size; i < len; i++) {
1256 map()->init_req(i, top());
1257 }
1258
1259 SafePointNode* entry_map = stop();
1260 return entry_map;
1261 }
1262
1263 //-----------------------------do_method_entry--------------------------------
1264 // Emit any code needed in the pseudo-block before BCI zero.
1265 // The main thing to do is lock the receiver of a synchronized method.
1266 void Parse::do_method_entry() {
1267 set_parse_bci(InvocationEntryBci); // Pseudo-BCP
1268 set_sp(0); // Java Stack Pointer
1269
1270 NOT_PRODUCT( count_compiled_calls(true/*at_method_entry*/, false/*is_inline*/); )
1271
1272 // Check if we need a membar at the beginning of the java.lang.Object
1273 // constructor to satisfy the memory model for strict fields.
1274 if (Arguments::is_valhalla_enabled() && method()->intrinsic_id() == vmIntrinsics::_Object_init) {
1275 Node* receiver_obj = local(0);
1276 const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1277 // If there's no exact type, check if the declared type has no implementors and add a dependency
1278 const TypeKlassPtr* klass_ptr = receiver_type->as_klass_type(/* try_for_exact= */ true);
1279 ciType* klass = klass_ptr->klass_is_exact() ? klass_ptr->exact_klass() : nullptr;
1280 if (klass != nullptr && klass->is_instance_klass()) {
1281 // Exact receiver type, check if there is a strict field
1282 ciInstanceKlass* holder = klass->as_instance_klass();
1283 for (int i = 0; i < holder->nof_nonstatic_fields(); i++) {
1284 ciField* field = holder->nonstatic_field_at(i);
1285 if (field->is_strict()) {
1286 // Found a strict field, a membar is needed
1287 AllocateNode* alloc = AllocateNode::Ideal_allocation(receiver_obj);
1288 insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease, receiver_obj);
1289 if (DoEscapeAnalysis && (alloc != nullptr)) {
1290 alloc->compute_MemBar_redundancy(method());
1291 }
1292 break;
1293 }
1294 }
1295 } else if (klass == nullptr) {
1296 // We can't statically determine the type of the receiver and therefore need
1297 // to put a membar here because it could have a strict field.
1298 insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease);
1299 }
1300 }
1301
1302 if (C->env()->dtrace_method_probes()) {
1303 make_dtrace_method_entry(method());
1304 }
1305
1306 #ifdef ASSERT
1307 // Narrow receiver type when it is too broad for the method being parsed.
1308 if (!method()->is_static()) {
1309 ciInstanceKlass* callee_holder = method()->holder();
1310 const Type* holder_type = TypeInstPtr::make(TypePtr::BotPTR, callee_holder, Type::trust_interfaces);
1311
1312 Node* receiver_obj = local(0);
1313 const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1314
1315 if (receiver_type != nullptr && !receiver_type->higher_equal(holder_type)) {
1316 // Receiver should always be a subtype of callee holder.
1317 // But, since C2 type system doesn't properly track interfaces,
1318 // the invariant can't be expressed in the type system for default methods.
1319 // Example: for unrelated C <: I and D <: I, (C `meet` D) = Object </: I.
1320 assert(callee_holder->is_interface(), "missing subtype check");
1321
1322 // Perform dynamic receiver subtype check against callee holder class w/ a halt on failure.
1323 Node* holder_klass = _gvn.makecon(TypeKlassPtr::make(callee_holder, Type::trust_interfaces));
1324 Node* not_subtype_ctrl = gen_subtype_check(receiver_obj, holder_klass);
1325 assert(!stopped(), "not a subtype");
1326
1327 halt(not_subtype_ctrl, frameptr(), "failed receiver subtype check");
1328 }
1329 }
1330 #endif // ASSERT
1331
1332 // If the method is synchronized, we need to construct a lock node, attach
1333 // it to the Start node, and pin it there.
1334 if (method()->is_synchronized()) {
1335 // Insert a FastLockNode right after the Start which takes as arguments
1336 // the current thread pointer, the "this" pointer & the address of the
1337 // stack slot pair used for the lock. The "this" pointer is a projection
1338 // off the start node, but the locking spot has to be constructed by
1339 // creating a ConLNode of 0, and boxing it with a BoxLockNode. The BoxLockNode
1340 // becomes the second argument to the FastLockNode call. The
1341 // FastLockNode becomes the new control parent to pin it to the start.
1342
1343 // Setup Object Pointer
1344 Node *lock_obj = nullptr;
1345 if (method()->is_static()) {
1346 ciInstance* mirror = _method->holder()->java_mirror();
1347 const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1348 lock_obj = makecon(t_lock);
1349 } else { // Else pass the "this" pointer,
1350 lock_obj = local(0); // which is Parm0 from StartNode
1351 assert(!_gvn.type(lock_obj)->make_oopptr()->can_be_inline_type(), "can't be an inline type");
1352 }
1353 // Clear out dead values from the debug info.
1354 kill_dead_locals();
1355 // Build the FastLockNode
1356 _synch_lock = shared_lock(lock_obj);
1357 // Check for bailout in shared_lock
1358 if (failing()) { return; }
1359 }
1360
1361 // Feed profiling data for parameters to the type system so it can
1362 // propagate it as speculative types
1363 record_profiled_parameters_for_speculation();
1364
1365 // More argument handling
1366 int arg_size = method()->arg_size();
1367 for (int i = 0; i < arg_size; i++) {
1368 Node* parm = local(i);
1369 const Type* t = _gvn.type(parm);
1370 if (t->is_inlinetypeptr()) {
1371 // If the parameter is a value object, try to scalarize it if we know that it is unrestricted (not early larval)
1372 // Parameters are non-larval except the receiver of a constructor, which must be an early larval object.
1373 if (!(method()->is_object_constructor() && i == 0)) {
1374 // Create InlineTypeNode from the oop and replace the parameter
1375 Node* vt = InlineTypeNode::make_from_oop(this, parm, t->inline_klass());
1376 replace_in_map(parm, vt);
1377 }
1378 } else if (UseTypeSpeculation && (i == (arg_size - 1)) && depth() == 1 && method()->has_vararg() && t->isa_aryptr()) {
1379 // Speculate on varargs Object array being the default array refined type. The assumption is
1380 // that a vararg method test(Object... o) is often called as test(o1, o2, o3). javac will
1381 // translate the call so that the caller will create a new default array of Object, put o1,
1382 // o2, o3 into the newly created array, then invoke the method test. This only makes sense if
1383 // the method we are parsing is the top-level method of the compilation unit. Otherwise, if
1384 // it is truly called according to our assumption, we must know the exact type of the
1385 // argument because the allocation happens inside the compilation unit.
1386 const TypePtr* spec_type = (t->speculative() != nullptr) ? t->speculative() : t->remove_speculative()->is_aryptr();
1387 ciSignature* method_signature = method()->signature();
1388 ciType* parm_citype = method_signature->type_at(method_signature->count() - 1);
1389 if (!parm_citype->is_obj_array_klass()) {
1390 continue;
1391 }
1392
1393 ciObjArrayKlass* spec_citype = ciObjArrayKlass::make(parm_citype->as_obj_array_klass()->element_klass(), true);
1394 const Type* improved_spec_type = TypeKlassPtr::make(spec_citype, Type::trust_interfaces)->as_instance_type();
1395 improved_spec_type = improved_spec_type->join(spec_type)->join(TypePtr::NOTNULL);
1396 if (improved_spec_type->empty()) {
1397 continue;
1398 }
1399
1400 const TypePtr* improved_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, improved_spec_type->is_ptr());
1401 improved_type = improved_type->join_speculative(t)->is_ptr();
1402 if (improved_type != t) {
1403 Node* cast = _gvn.transform(new CheckCastPPNode(control(), parm, improved_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1404 replace_in_map(parm, cast);
1405 }
1406 }
1407 }
1408 }
1409
1410 //------------------------------init_blocks------------------------------------
1411 // Initialize our parser map to contain the types/monitors at method entry.
1412 void Parse::init_blocks() {
1413 // Create the blocks.
1414 _block_count = flow()->block_count();
1415 _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1416
1417 // Initialize the structs.
1418 for (int rpo = 0; rpo < block_count(); rpo++) {
1419 Block* block = rpo_at(rpo);
1420 new(block) Block(this, rpo);
1421 }
1422
1423 // Collect predecessor and successor information.
1424 for (int rpo = 0; rpo < block_count(); rpo++) {
1425 Block* block = rpo_at(rpo);
1426 block->init_graph(this);
1427 }
1428 }
1429
1430 //-------------------------------init_node-------------------------------------
1431 Parse::Block::Block(Parse* outer, int rpo) : _live_locals() {
1432 _flow = outer->flow()->rpo_at(rpo);
1433 _pred_count = 0;
1434 _preds_parsed = 0;
1435 _count = 0;
1436 _is_parsed = false;
1437 _is_handler = false;
1438 _has_merged_backedge = false;
1439 _start_map = nullptr;
1440 _has_predicates = false;
1441 _num_successors = 0;
1442 _all_successors = 0;
1443 _successors = nullptr;
1444 assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1445 assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1446 assert(_live_locals.size() == 0, "sanity");
1447
1448 // entry point has additional predecessor
1449 if (flow()->is_start()) _pred_count++;
1450 assert(flow()->is_start() == (this == outer->start_block()), "");
1451 }
1452
1453 //-------------------------------init_graph------------------------------------
1454 void Parse::Block::init_graph(Parse* outer) {
1455 // Create the successor list for this parser block.
1456 GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1457 GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1458 int ns = tfs->length();
1459 int ne = tfe->length();
1460 _num_successors = ns;
1461 _all_successors = ns+ne;
1462 _successors = (ns+ne == 0) ? nullptr : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1463 int p = 0;
1464 for (int i = 0; i < ns+ne; i++) {
1465 ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1466 Block* block2 = outer->rpo_at(tf2->rpo());
1467 _successors[i] = block2;
1468
1469 // Accumulate pred info for the other block, too.
1470 // Note: We also need to set _pred_count for exception blocks since they could
1471 // also have normal predecessors (reached without athrow by an explicit jump).
1472 // This also means that next_path_num can be called along exception paths.
1473 block2->_pred_count++;
1474 if (i >= ns) {
1475 block2->_is_handler = true;
1476 }
1477
1478 #ifdef ASSERT
1479 // A block's successors must be distinguishable by BCI.
1480 // That is, no bytecode is allowed to branch to two different
1481 // clones of the same code location.
1482 for (int j = 0; j < i; j++) {
1483 Block* block1 = _successors[j];
1484 if (block1 == block2) continue; // duplicates are OK
1485 assert(block1->start() != block2->start(), "successors have unique bcis");
1486 }
1487 #endif
1488 }
1489 }
1490
1491 //---------------------------successor_for_bci---------------------------------
1492 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1493 for (int i = 0; i < all_successors(); i++) {
1494 Block* block2 = successor_at(i);
1495 if (block2->start() == bci) return block2;
1496 }
1497 // We can actually reach here if ciTypeFlow traps out a block
1498 // due to an unloaded class, and concurrently with compilation the
1499 // class is then loaded, so that a later phase of the parser is
1500 // able to see more of the bytecode CFG. Or, the flow pass and
1501 // the parser can have a minor difference of opinion about executability
1502 // of bytecodes. For example, "obj.field = null" is executable even
1503 // if the field's type is an unloaded class; the flow pass used to
1504 // make a trap for such code.
1505 return nullptr;
1506 }
1507
1508
1509 //-----------------------------stack_type_at-----------------------------------
1510 const Type* Parse::Block::stack_type_at(int i) const {
1511 return get_type(flow()->stack_type_at(i));
1512 }
1513
1514
1515 //-----------------------------local_type_at-----------------------------------
1516 const Type* Parse::Block::local_type_at(int i) const {
1517 // Make dead locals fall to bottom.
1518 if (_live_locals.size() == 0) {
1519 MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1520 // This bitmap can be zero length if we saw a breakpoint.
1521 // In such cases, pretend they are all live.
1522 ((Block*)this)->_live_locals = live_locals;
1523 }
1524 if (_live_locals.size() > 0 && !_live_locals.at(i))
1525 return Type::BOTTOM;
1526
1527 return get_type(flow()->local_type_at(i));
1528 }
1529
1530
1531 #ifndef PRODUCT
1532
1533 //----------------------------name_for_bc--------------------------------------
1534 // helper method for BytecodeParseHistogram
1535 static const char* name_for_bc(int i) {
1536 return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1537 }
1538
1539 //----------------------------BytecodeParseHistogram------------------------------------
1540 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1541 _parser = p;
1542 _compiler = c;
1543 if( ! _initialized ) { _initialized = true; reset(); }
1544 }
1545
1546 //----------------------------current_count------------------------------------
1547 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1548 switch( bph_type ) {
1549 case BPH_transforms: { return _parser->gvn().made_progress(); }
1550 case BPH_values: { return _parser->gvn().made_new_values(); }
1551 default: { ShouldNotReachHere(); return 0; }
1552 }
1553 }
1554
1555 //----------------------------initialized--------------------------------------
1556 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1557
1558 //----------------------------reset--------------------------------------------
1559 void Parse::BytecodeParseHistogram::reset() {
1560 int i = Bytecodes::number_of_codes;
1561 while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1562 }
1563
1564 //----------------------------set_initial_state--------------------------------
1565 // Record info when starting to parse one bytecode
1566 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1567 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1568 _initial_bytecode = bc;
1569 _initial_node_count = _compiler->unique();
1570 _initial_transforms = current_count(BPH_transforms);
1571 _initial_values = current_count(BPH_values);
1572 }
1573 }
1574
1575 //----------------------------record_change--------------------------------
1576 // Record results of parsing one bytecode
1577 void Parse::BytecodeParseHistogram::record_change() {
1578 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1579 ++_bytecodes_parsed[_initial_bytecode];
1580 _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1581 _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1582 _new_values [_initial_bytecode] += (current_count(BPH_values) - _initial_values);
1583 }
1584 }
1585
1586
1587 //----------------------------print--------------------------------------------
1588 void Parse::BytecodeParseHistogram::print(float cutoff) {
1589 ResourceMark rm;
1590 // print profile
1591 int total = 0;
1592 int i = 0;
1593 for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1594 int abs_sum = 0;
1595 tty->cr(); //0123456789012345678901234567890123456789012345678901234567890123456789
1596 tty->print_cr("Histogram of %d parsed bytecodes:", total);
1597 if( total == 0 ) { return; }
1598 tty->cr();
1599 tty->print_cr("absolute: count of compiled bytecodes of this type");
1600 tty->print_cr("relative: percentage contribution to compiled nodes");
1601 tty->print_cr("nodes : Average number of nodes constructed per bytecode");
1602 tty->print_cr("rnodes : Significance towards total nodes constructed, (nodes*relative)");
1603 tty->print_cr("transforms: Average amount of transform progress per bytecode compiled");
1604 tty->print_cr("values : Average number of node values improved per bytecode");
1605 tty->print_cr("name : Bytecode name");
1606 tty->cr();
1607 tty->print_cr(" absolute relative nodes rnodes transforms values name");
1608 tty->print_cr("----------------------------------------------------------------------");
1609 while (--i > 0) {
1610 int abs = _bytecodes_parsed[i];
1611 float rel = abs * 100.0F / total;
1612 float nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1613 float rnodes = _bytecodes_parsed[i] == 0 ? 0 : rel * nodes;
1614 float xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1615 float values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values [i])/_bytecodes_parsed[i];
1616 if (cutoff <= rel) {
1617 tty->print_cr("%10d %7.2f%% %6.1f %6.2f %6.1f %6.1f %s", abs, rel, nodes, rnodes, xforms, values, name_for_bc(i));
1618 abs_sum += abs;
1619 }
1620 }
1621 tty->print_cr("----------------------------------------------------------------------");
1622 float rel_sum = abs_sum * 100.0F / total;
1623 tty->print_cr("%10d %7.2f%% (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1624 tty->print_cr("----------------------------------------------------------------------");
1625 tty->cr();
1626 }
1627 #endif
1628
1629 //----------------------------load_state_from----------------------------------
1630 // Load block/map/sp. But not do not touch iter/bci.
1631 void Parse::load_state_from(Block* block) {
1632 set_block(block);
1633 // load the block's JVM state:
1634 set_map(block->start_map());
1635 set_sp( block->start_sp());
1636 }
1637
1638
1639 //-----------------------------record_state------------------------------------
1640 void Parse::Block::record_state(Parse* p) {
1641 assert(!is_merged(), "can only record state once, on 1st inflow");
1642 assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1643 set_start_map(p->stop());
1644 }
1645
1646
1647 //------------------------------do_one_block-----------------------------------
1648 void Parse::do_one_block() {
1649 if (TraceOptoParse) {
1650 Block *b = block();
1651 int ns = b->num_successors();
1652 int nt = b->all_successors();
1653
1654 tty->print("Parsing block #%d at bci [%d,%d), successors:",
1655 block()->rpo(), block()->start(), block()->limit());
1656 for (int i = 0; i < nt; i++) {
1657 tty->print((( i < ns) ? " %d" : " %d(exception block)"), b->successor_at(i)->rpo());
1658 }
1659 if (b->is_loop_head()) {
1660 tty->print(" loop head");
1661 }
1662 if (b->is_irreducible_loop_entry()) {
1663 tty->print(" irreducible");
1664 }
1665 tty->cr();
1666 }
1667
1668 assert(block()->is_merged(), "must be merged before being parsed");
1669 block()->mark_parsed();
1670
1671 // Set iterator to start of block.
1672 iter().reset_to_bci(block()->start());
1673
1674 if (ProfileExceptionHandlers && block()->is_handler()) {
1675 ciMethodData* methodData = method()->method_data();
1676 if (methodData->is_mature()) {
1677 ciBitData data = methodData->exception_handler_bci_to_data(block()->start());
1678 if (!data.exception_handler_entered() || StressPrunedExceptionHandlers) {
1679 // dead catch block
1680 // Emit an uncommon trap instead of processing the block.
1681 set_parse_bci(block()->start());
1682 uncommon_trap(Deoptimization::Reason_unreached,
1683 Deoptimization::Action_reinterpret,
1684 nullptr, "dead catch block");
1685 return;
1686 }
1687 }
1688 }
1689
1690 CompileLog* log = C->log();
1691
1692 // Parse bytecodes
1693 while (!stopped() && !failing()) {
1694 iter().next();
1695
1696 // Learn the current bci from the iterator:
1697 set_parse_bci(iter().cur_bci());
1698
1699 if (bci() == block()->limit()) {
1700 // Do not walk into the next block until directed by do_all_blocks.
1701 merge(bci());
1702 break;
1703 }
1704 assert(bci() < block()->limit(), "bci still in block");
1705
1706 if (log != nullptr) {
1707 // Output an optional context marker, to help place actions
1708 // that occur during parsing of this BC. If there is no log
1709 // output until the next context string, this context string
1710 // will be silently ignored.
1711 log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1712 }
1713
1714 if (block()->has_trap_at(bci())) {
1715 // We must respect the flow pass's traps, because it will refuse
1716 // to produce successors for trapping blocks.
1717 int trap_index = block()->flow()->trap_index();
1718 assert(trap_index != 0, "trap index must be valid");
1719 uncommon_trap(trap_index);
1720 break;
1721 }
1722
1723 NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1724
1725 #ifdef ASSERT
1726 int pre_bc_sp = sp();
1727 int inputs, depth;
1728 bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1729 assert(!have_se || pre_bc_sp >= inputs, "have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs);
1730 #endif //ASSERT
1731
1732 do_one_bytecode();
1733 if (failing()) return;
1734
1735 assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1736 "incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth);
1737
1738 do_exceptions();
1739
1740 NOT_PRODUCT( parse_histogram()->record_change(); );
1741
1742 if (log != nullptr)
1743 log->clear_context(); // skip marker if nothing was printed
1744
1745 // Fall into next bytecode. Each bytecode normally has 1 sequential
1746 // successor which is typically made ready by visiting this bytecode.
1747 // If the successor has several predecessors, then it is a merge
1748 // point, starts a new basic block, and is handled like other basic blocks.
1749 }
1750 }
1751
1752
1753 //------------------------------merge------------------------------------------
1754 void Parse::set_parse_bci(int bci) {
1755 set_bci(bci);
1756 Node_Notes* nn = C->default_node_notes();
1757 if (nn == nullptr) return;
1758
1759 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1760 if (!DebugInlinedCalls && depth() > 1) {
1761 return;
1762 }
1763
1764 // Update the JVMS annotation, if present.
1765 JVMState* jvms = nn->jvms();
1766 if (jvms != nullptr && jvms->bci() != bci) {
1767 // Update the JVMS.
1768 jvms = jvms->clone_shallow(C);
1769 jvms->set_bci(bci);
1770 nn->set_jvms(jvms);
1771 }
1772 }
1773
1774 //------------------------------merge------------------------------------------
1775 // Merge the current mapping into the basic block starting at bci
1776 void Parse::merge(int target_bci) {
1777 Block* target = successor_for_bci(target_bci);
1778 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1779 assert(!target->is_ready(), "our arrival must be expected");
1780 int pnum = target->next_path_num();
1781 merge_common(target, pnum);
1782 }
1783
1784 //-------------------------merge_new_path--------------------------------------
1785 // Merge the current mapping into the basic block, using a new path
1786 void Parse::merge_new_path(int target_bci) {
1787 Block* target = successor_for_bci(target_bci);
1788 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1789 assert(!target->is_ready(), "new path into frozen graph");
1790 int pnum = target->add_new_path();
1791 merge_common(target, pnum);
1792 }
1793
1794 //-------------------------merge_exception-------------------------------------
1795 // Merge the current mapping into the basic block starting at bci
1796 // The ex_oop must be pushed on the stack, unlike throw_to_exit.
1797 void Parse::merge_exception(int target_bci) {
1798 #ifdef ASSERT
1799 if (target_bci <= bci()) {
1800 C->set_exception_backedge();
1801 }
1802 #endif
1803 assert(sp() == 1, "must have only the throw exception on the stack");
1804 Block* target = successor_for_bci(target_bci);
1805 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1806 assert(target->is_handler(), "exceptions are handled by special blocks");
1807 int pnum = target->add_new_path();
1808 merge_common(target, pnum);
1809 }
1810
1811 //--------------------handle_missing_successor---------------------------------
1812 void Parse::handle_missing_successor(int target_bci) {
1813 #ifndef PRODUCT
1814 Block* b = block();
1815 int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1816 tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1817 #endif
1818 ShouldNotReachHere();
1819 }
1820
1821 //--------------------------merge_common---------------------------------------
1822 void Parse::merge_common(Parse::Block* target, int pnum) {
1823 if (TraceOptoParse) {
1824 tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1825 }
1826
1827 // Zap extra stack slots to top
1828 assert(sp() == target->start_sp(), "");
1829 clean_stack(sp());
1830
1831 // Check for merge conflicts involving inline types
1832 JVMState* old_jvms = map()->jvms();
1833 int old_bci = bci();
1834 JVMState* tmp_jvms = old_jvms->clone_shallow(C);
1835 tmp_jvms->set_should_reexecute(true);
1836 tmp_jvms->bind_map(map());
1837 // Execution needs to restart a the next bytecode (entry of next
1838 // block)
1839 if (target->is_merged() ||
1840 pnum > PhiNode::Input ||
1841 target->is_handler() ||
1842 target->is_loop_head()) {
1843 set_parse_bci(target->start());
1844 for (uint j = TypeFunc::Parms; j < map()->req(); j++) {
1845 Node* n = map()->in(j); // Incoming change to target state.
1846 const Type* t = nullptr;
1847 ciType* ct = nullptr;
1848 if (tmp_jvms->is_loc(j)) {
1849 int loc_idx = j - tmp_jvms->locoff();
1850 t = target->local_type_at(loc_idx);
1851 ct = target->flow()->local_type_at(loc_idx);
1852 } else if (tmp_jvms->is_stk(j) && j < (uint)sp() + tmp_jvms->stkoff()) {
1853 int stk_idx = j - tmp_jvms->stkoff();
1854 t = target->stack_type_at(stk_idx);
1855 ct = target->flow()->stack_type_at(stk_idx);
1856 }
1857 if (t != nullptr && t != Type::BOTTOM) {
1858 // An object can appear in the JVMS as either an oop or an InlineTypeNode. If the merge is
1859 // an InlineTypeNode, we need all the merge inputs to be InlineTypeNodes. Else, if the
1860 // merge is an oop, each merge input needs to be either an oop or an buffered
1861 // InlineTypeNode.
1862 if (!t->is_inlinetypeptr()) {
1863 // The merge cannot be an InlineTypeNode, ensure the input is buffered if it is an
1864 // InlineTypeNode
1865 if (n->is_InlineType()) {
1866 map()->set_req(j, n->as_InlineType()->buffer(this));
1867 }
1868 } else {
1869 // Scalarize the value object if it is not larval
1870 if (!n->is_InlineType() && !ct->is_early_larval()) {
1871 assert(_gvn.type(n) == TypePtr::NULL_PTR, "must be a null constant");
1872 map()->set_req(j, InlineTypeNode::make_null(_gvn, t->inline_klass()));
1873 }
1874 }
1875 }
1876 }
1877 }
1878 old_jvms->bind_map(map());
1879 set_parse_bci(old_bci);
1880
1881 if (!target->is_merged()) { // No prior mapping at this bci
1882 if (TraceOptoParse) { tty->print(" with empty state"); }
1883
1884 // If this path is dead, do not bother capturing it as a merge.
1885 // It is "as if" we had 1 fewer predecessors from the beginning.
1886 if (stopped()) {
1887 if (TraceOptoParse) tty->print_cr(", but path is dead and doesn't count");
1888 return;
1889 }
1890
1891 // Make a region if we know there are multiple or unpredictable inputs.
1892 // (Also, if this is a plain fall-through, we might see another region,
1893 // which must not be allowed into this block's map.)
1894 if (pnum > PhiNode::Input // Known multiple inputs.
1895 || target->is_handler() // These have unpredictable inputs.
1896 || target->is_loop_head() // Known multiple inputs
1897 || control()->is_Region()) { // We must hide this guy.
1898
1899 int current_bci = bci();
1900 set_parse_bci(target->start()); // Set target bci
1901 if (target->is_SEL_head()) {
1902 DEBUG_ONLY( target->mark_merged_backedge(block()); )
1903 if (target->start() == 0) {
1904 // Add Parse Predicates for the special case when
1905 // there are backbranches to the method entry.
1906 add_parse_predicates();
1907 }
1908 }
1909 // Add a Region to start the new basic block. Phis will be added
1910 // later lazily.
1911 int edges = target->pred_count();
1912 if (edges < pnum) edges = pnum; // might be a new path!
1913 RegionNode *r = new RegionNode(edges+1);
1914 gvn().set_type(r, Type::CONTROL);
1915 record_for_igvn(r);
1916 // zap all inputs to null for debugging (done in Node(uint) constructor)
1917 // for (int j = 1; j < edges+1; j++) { r->init_req(j, nullptr); }
1918 r->init_req(pnum, control());
1919 set_control(r);
1920 target->copy_irreducible_status_to(r, jvms());
1921 set_parse_bci(current_bci); // Restore bci
1922 }
1923
1924 // Convert the existing Parser mapping into a mapping at this bci.
1925 store_state_to(target);
1926 assert(target->is_merged(), "do not come here twice");
1927
1928 } else { // Prior mapping at this bci
1929 if (TraceOptoParse) { tty->print(" with previous state"); }
1930 #ifdef ASSERT
1931 if (target->is_SEL_head()) {
1932 target->mark_merged_backedge(block());
1933 }
1934 #endif
1935
1936 // We must not manufacture more phis if the target is already parsed.
1937 bool nophi = target->is_parsed();
1938
1939 SafePointNode* newin = map();// Hang on to incoming mapping
1940 Block* save_block = block(); // Hang on to incoming block;
1941 load_state_from(target); // Get prior mapping
1942
1943 assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
1944 assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
1945 assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
1946 assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
1947
1948 // Iterate over my current mapping and the old mapping.
1949 // Where different, insert Phi functions.
1950 // Use any existing Phi functions.
1951 assert(control()->is_Region(), "must be merging to a region");
1952 RegionNode* r = control()->as_Region();
1953
1954 // Compute where to merge into
1955 // Merge incoming control path
1956 r->init_req(pnum, newin->control());
1957
1958 if (pnum == 1) { // Last merge for this Region?
1959 if (!block()->flow()->is_irreducible_loop_secondary_entry()) {
1960 Node* result = _gvn.transform(r);
1961 if (r != result && TraceOptoParse) {
1962 tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
1963 }
1964 }
1965 record_for_igvn(r);
1966 }
1967
1968 // Update all the non-control inputs to map:
1969 assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
1970 bool check_elide_phi = target->is_SEL_backedge(save_block);
1971 bool last_merge = (pnum == PhiNode::Input);
1972 for (uint j = 1; j < newin->req(); j++) {
1973 Node* m = map()->in(j); // Current state of target.
1974 Node* n = newin->in(j); // Incoming change to target state.
1975 Node* phi;
1976 if (m->is_Phi() && m->as_Phi()->region() == r) {
1977 phi = m;
1978 } else if (m->is_InlineType() && m->as_InlineType()->has_phi_inputs(r)) {
1979 phi = m;
1980 } else {
1981 phi = nullptr;
1982 }
1983 if (m != n) { // Different; must merge
1984 switch (j) {
1985 // Frame pointer and Return Address never changes
1986 case TypeFunc::FramePtr:// Drop m, use the original value
1987 case TypeFunc::ReturnAdr:
1988 break;
1989 case TypeFunc::Memory: // Merge inputs to the MergeMem node
1990 assert(phi == nullptr, "the merge contains phis, not vice versa");
1991 merge_memory_edges(n->as_MergeMem(), pnum, nophi);
1992 continue;
1993 default: // All normal stuff
1994 if (phi == nullptr) {
1995 const JVMState* jvms = map()->jvms();
1996 if (EliminateNestedLocks &&
1997 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
1998 // BoxLock nodes are not commoning when EliminateNestedLocks is on.
1999 // Use old BoxLock node as merged box.
2000 assert(newin->jvms()->is_monitor_box(j), "sanity");
2001 // This assert also tests that nodes are BoxLock.
2002 assert(BoxLockNode::same_slot(n, m), "sanity");
2003 BoxLockNode* old_box = m->as_BoxLock();
2004 if (n->as_BoxLock()->is_unbalanced() && !old_box->is_unbalanced()) {
2005 // Preserve Unbalanced status.
2006 //
2007 // `old_box` can have only Regular or Coarsened status
2008 // because this code is executed only during Parse phase and
2009 // Incremental Inlining before EA and Macro nodes elimination.
2010 //
2011 // Incremental Inlining is executed after IGVN optimizations
2012 // during which BoxLock can be marked as Coarsened.
2013 old_box->set_coarsened(); // Verifies state
2014 old_box->set_unbalanced();
2015 }
2016 C->gvn_replace_by(n, m);
2017 } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
2018 phi = ensure_phi(j, nophi);
2019 }
2020 }
2021 break;
2022 }
2023 }
2024 // At this point, n might be top if:
2025 // - there is no phi (because TypeFlow detected a conflict), or
2026 // - the corresponding control edges is top (a dead incoming path)
2027 // It is a bug if we create a phi which sees a garbage value on a live path.
2028
2029 // Merging two inline types?
2030 if (phi != nullptr && phi->is_InlineType()) {
2031 // Reload current state because it may have been updated by ensure_phi
2032 assert(phi == map()->in(j), "unexpected value in map");
2033 assert(phi->as_InlineType()->has_phi_inputs(r), "");
2034 InlineTypeNode* vtm = phi->as_InlineType(); // Current inline type
2035 InlineTypeNode* vtn = n->as_InlineType(); // Incoming inline type
2036 assert(vtm == phi, "Inline type should have Phi input");
2037
2038 #ifdef ASSERT
2039 if (TraceOptoParse) {
2040 tty->print_cr("\nMerging inline types");
2041 tty->print_cr("Current:");
2042 vtm->dump(2);
2043 tty->print_cr("Incoming:");
2044 vtn->dump(2);
2045 tty->cr();
2046 }
2047 #endif
2048 // Do the merge
2049 vtm->merge_with(&_gvn, vtn, pnum, last_merge);
2050 if (last_merge) {
2051 map()->set_req(j, _gvn.transform(vtm));
2052 record_for_igvn(vtm);
2053 }
2054 } else if (phi != nullptr) {
2055 assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
2056 assert(phi->as_Phi()->region() == r, "");
2057 phi->set_req(pnum, n); // Then add 'n' to the merge
2058 if (last_merge) {
2059 // Last merge for this Phi.
2060 // So far, Phis have had a reasonable type from ciTypeFlow.
2061 // Now _gvn will join that with the meet of current inputs.
2062 // BOTTOM is never permissible here, 'cause pessimistically
2063 // Phis of pointers cannot lose the basic pointer type.
2064 DEBUG_ONLY(const Type* bt1 = phi->bottom_type());
2065 assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
2066 map()->set_req(j, _gvn.transform(phi));
2067 DEBUG_ONLY(const Type* bt2 = phi->bottom_type());
2068 assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
2069 record_for_igvn(phi);
2070 }
2071 }
2072 } // End of for all values to be merged
2073
2074 if (last_merge && !r->in(0)) { // The occasional useless Region
2075 assert(control() == r, "");
2076 set_control(r->nonnull_req());
2077 }
2078
2079 map()->merge_replaced_nodes_with(newin);
2080
2081 // newin has been subsumed into the lazy merge, and is now dead.
2082 set_block(save_block);
2083
2084 stop(); // done with this guy, for now
2085 }
2086
2087 if (TraceOptoParse) {
2088 tty->print_cr(" on path %d", pnum);
2089 }
2090
2091 // Done with this parser state.
2092 assert(stopped(), "");
2093 }
2094
2095
2096 //--------------------------merge_memory_edges---------------------------------
2097 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
2098 // (nophi means we must not create phis, because we already parsed here)
2099 assert(n != nullptr, "");
2100 // Merge the inputs to the MergeMems
2101 MergeMemNode* m = merged_memory();
2102
2103 assert(control()->is_Region(), "must be merging to a region");
2104 RegionNode* r = control()->as_Region();
2105
2106 PhiNode* base = nullptr;
2107 MergeMemNode* remerge = nullptr;
2108 for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
2109 Node *p = mms.force_memory();
2110 Node *q = mms.memory2();
2111 if (mms.is_empty() && nophi) {
2112 // Trouble: No new splits allowed after a loop body is parsed.
2113 // Instead, wire the new split into a MergeMem on the backedge.
2114 // The optimizer will sort it out, slicing the phi.
2115 if (remerge == nullptr) {
2116 guarantee(base != nullptr, "");
2117 assert(base->in(0) != nullptr, "should not be xformed away");
2118 remerge = MergeMemNode::make(base->in(pnum));
2119 gvn().set_type(remerge, Type::MEMORY);
2120 base->set_req(pnum, remerge);
2121 }
2122 remerge->set_memory_at(mms.alias_idx(), q);
2123 continue;
2124 }
2125 assert(!q->is_MergeMem(), "");
2126 PhiNode* phi;
2127 if (p != q) {
2128 phi = ensure_memory_phi(mms.alias_idx(), nophi);
2129 } else {
2130 if (p->is_Phi() && p->as_Phi()->region() == r)
2131 phi = p->as_Phi();
2132 else
2133 phi = nullptr;
2134 }
2135 // Insert q into local phi
2136 if (phi != nullptr) {
2137 assert(phi->region() == r, "");
2138 p = phi;
2139 phi->set_req(pnum, q);
2140 if (mms.at_base_memory()) {
2141 base = phi; // delay transforming it
2142 } else if (pnum == 1) {
2143 record_for_igvn(phi);
2144 p = _gvn.transform(phi);
2145 }
2146 mms.set_memory(p);// store back through the iterator
2147 }
2148 }
2149 // Transform base last, in case we must fiddle with remerging.
2150 if (base != nullptr && pnum == 1) {
2151 record_for_igvn(base);
2152 m->set_base_memory(_gvn.transform(base));
2153 }
2154 }
2155
2156
2157 //------------------------ensure_phis_everywhere-------------------------------
2158 void Parse::ensure_phis_everywhere() {
2159 ensure_phi(TypeFunc::I_O);
2160
2161 // Ensure a phi on all currently known memories.
2162 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
2163 ensure_memory_phi(mms.alias_idx());
2164 DEBUG_ONLY(mms.set_memory()); // keep the iterator happy
2165 }
2166
2167 // Note: This is our only chance to create phis for memory slices.
2168 // If we miss a slice that crops up later, it will have to be
2169 // merged into the base-memory phi that we are building here.
2170 // Later, the optimizer will comb out the knot, and build separate
2171 // phi-loops for each memory slice that matters.
2172
2173 // Monitors must nest nicely and not get confused amongst themselves.
2174 // Phi-ify everything up to the monitors, though.
2175 uint monoff = map()->jvms()->monoff();
2176 uint nof_monitors = map()->jvms()->nof_monitors();
2177
2178 assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
2179 bool check_elide_phi = block()->is_SEL_head();
2180 for (uint i = TypeFunc::Parms; i < monoff; i++) {
2181 if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
2182 ensure_phi(i);
2183 }
2184 }
2185
2186 // Even monitors need Phis, though they are well-structured.
2187 // This is true for OSR methods, and also for the rare cases where
2188 // a monitor object is the subject of a replace_in_map operation.
2189 // See bugs 4426707 and 5043395.
2190 for (uint m = 0; m < nof_monitors; m++) {
2191 ensure_phi(map()->jvms()->monitor_obj_offset(m));
2192 }
2193 }
2194
2195
2196 //-----------------------------add_new_path------------------------------------
2197 // Add a previously unaccounted predecessor to this block.
2198 int Parse::Block::add_new_path() {
2199 // If there is no map, return the lowest unused path number.
2200 if (!is_merged()) return pred_count()+1; // there will be a map shortly
2201
2202 SafePointNode* map = start_map();
2203 if (!map->control()->is_Region())
2204 return pred_count()+1; // there may be a region some day
2205 RegionNode* r = map->control()->as_Region();
2206
2207 // Add new path to the region.
2208 uint pnum = r->req();
2209 r->add_req(nullptr);
2210
2211 for (uint i = 1; i < map->req(); i++) {
2212 Node* n = map->in(i);
2213 if (i == TypeFunc::Memory) {
2214 // Ensure a phi on all currently known memories.
2215 for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
2216 Node* phi = mms.memory();
2217 if (phi->is_Phi() && phi->as_Phi()->region() == r) {
2218 assert(phi->req() == pnum, "must be same size as region");
2219 phi->add_req(nullptr);
2220 }
2221 }
2222 } else {
2223 if (n->is_Phi() && n->as_Phi()->region() == r) {
2224 assert(n->req() == pnum, "must be same size as region");
2225 n->add_req(nullptr);
2226 } else if (n->is_InlineType() && n->as_InlineType()->has_phi_inputs(r)) {
2227 n->as_InlineType()->add_new_path(r);
2228 }
2229 }
2230 }
2231
2232 return pnum;
2233 }
2234
2235 //------------------------------ensure_phi-------------------------------------
2236 // Turn the idx'th entry of the current map into a Phi
2237 Node* Parse::ensure_phi(int idx, bool nocreate) {
2238 SafePointNode* map = this->map();
2239 Node* region = map->control();
2240 assert(region->is_Region(), "");
2241
2242 Node* o = map->in(idx);
2243 assert(o != nullptr, "");
2244
2245 if (o == top()) return nullptr; // TOP always merges into TOP
2246
2247 if (o->is_Phi() && o->as_Phi()->region() == region) {
2248 return o->as_Phi();
2249 }
2250 InlineTypeNode* vt = o->isa_InlineType();
2251 if (vt != nullptr && vt->has_phi_inputs(region)) {
2252 return vt;
2253 }
2254
2255 // Now use a Phi here for merging
2256 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2257 const JVMState* jvms = map->jvms();
2258 const Type* t = nullptr;
2259 if (jvms->is_loc(idx)) {
2260 t = block()->local_type_at(idx - jvms->locoff());
2261 } else if (jvms->is_stk(idx)) {
2262 t = block()->stack_type_at(idx - jvms->stkoff());
2263 } else if (jvms->is_mon(idx)) {
2264 assert(!jvms->is_monitor_box(idx), "no phis for boxes");
2265 t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
2266 } else if ((uint)idx < TypeFunc::Parms) {
2267 t = o->bottom_type(); // Type::RETURN_ADDRESS or such-like.
2268 } else {
2269 assert(false, "no type information for this phi");
2270 }
2271
2272 // If the type falls to bottom, then this must be a local that
2273 // is already dead or is mixing ints and oops or some such.
2274 // Forcing it to top makes it go dead.
2275 if (t == Type::BOTTOM) {
2276 map->set_req(idx, top());
2277 return nullptr;
2278 }
2279
2280 // Do not create phis for top either.
2281 // A top on a non-null control flow must be an unused even after the.phi.
2282 if (t == Type::TOP || t == Type::HALF) {
2283 map->set_req(idx, top());
2284 return nullptr;
2285 }
2286
2287 if (vt != nullptr && t->is_inlinetypeptr()) {
2288 // Inline types are merged by merging their field values.
2289 // Create a cloned InlineTypeNode with phi inputs that
2290 // represents the merged inline type and update the map.
2291 vt = vt->clone_with_phis(&_gvn, region);
2292 map->set_req(idx, vt);
2293 return vt;
2294 } else {
2295 PhiNode* phi = PhiNode::make(region, o, t);
2296 gvn().set_type(phi, t);
2297 if (C->do_escape_analysis()) record_for_igvn(phi);
2298 map->set_req(idx, phi);
2299 return phi;
2300 }
2301 }
2302
2303 //--------------------------ensure_memory_phi----------------------------------
2304 // Turn the idx'th slice of the current memory into a Phi
2305 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
2306 MergeMemNode* mem = merged_memory();
2307 Node* region = control();
2308 assert(region->is_Region(), "");
2309
2310 Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
2311 assert(o != nullptr && o != top(), "");
2312
2313 PhiNode* phi;
2314 if (o->is_Phi() && o->as_Phi()->region() == region) {
2315 phi = o->as_Phi();
2316 if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
2317 // clone the shared base memory phi to make a new memory split
2318 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2319 const Type* t = phi->bottom_type();
2320 const TypePtr* adr_type = C->get_adr_type(idx);
2321 phi = phi->slice_memory(adr_type);
2322 gvn().set_type(phi, t);
2323 }
2324 return phi;
2325 }
2326
2327 // Now use a Phi here for merging
2328 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2329 const Type* t = o->bottom_type();
2330 const TypePtr* adr_type = C->get_adr_type(idx);
2331 phi = PhiNode::make(region, o, t, adr_type);
2332 gvn().set_type(phi, t);
2333 if (idx == Compile::AliasIdxBot)
2334 mem->set_base_memory(phi);
2335 else
2336 mem->set_memory_at(idx, phi);
2337 return phi;
2338 }
2339
2340 //------------------------------call_register_finalizer-----------------------
2341 // Check the klass of the receiver and call register_finalizer if the
2342 // class need finalization.
2343 void Parse::call_register_finalizer() {
2344 Node* receiver = local(0);
2345 assert(receiver != nullptr && receiver->bottom_type()->isa_instptr() != nullptr,
2346 "must have non-null instance type");
2347
2348 const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
2349 if (tinst != nullptr && tinst->is_loaded() && !tinst->klass_is_exact()) {
2350 // The type isn't known exactly so see if CHA tells us anything.
2351 ciInstanceKlass* ik = tinst->instance_klass();
2352 if (!Dependencies::has_finalizable_subclass(ik)) {
2353 // No finalizable subclasses so skip the dynamic check.
2354 C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2355 return;
2356 }
2357 }
2358
2359 // Insert a dynamic test for whether the instance needs
2360 // finalization. In general this will fold up since the concrete
2361 // class is often visible so the access flags are constant.
2362 Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2363 Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2364
2365 Node* access_flags_addr = basic_plus_adr(top(), klass, in_bytes(Klass::misc_flags_offset()));
2366 Node* access_flags = make_load(nullptr, access_flags_addr, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
2367
2368 Node* mask = _gvn.transform(new AndINode(access_flags, intcon(KlassFlags::_misc_has_finalizer)));
2369 Node* check = _gvn.transform(new CmpINode(mask, intcon(0)));
2370 Node* test = _gvn.transform(new BoolNode(check, BoolTest::ne));
2371
2372 IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2373
2374 RegionNode* result_rgn = new RegionNode(3);
2375 record_for_igvn(result_rgn);
2376
2377 Node *skip_register = _gvn.transform(new IfFalseNode(iff));
2378 result_rgn->init_req(1, skip_register);
2379
2380 Node *needs_register = _gvn.transform(new IfTrueNode(iff));
2381 set_control(needs_register);
2382 if (stopped()) {
2383 // There is no slow path.
2384 result_rgn->init_req(2, top());
2385 } else {
2386 Node *call = make_runtime_call(RC_NO_LEAF,
2387 OptoRuntime::register_finalizer_Type(),
2388 OptoRuntime::register_finalizer_Java(),
2389 nullptr, TypePtr::BOTTOM,
2390 receiver);
2391 make_slow_call_ex(call, env()->Throwable_klass(), true);
2392
2393 Node* fast_io = call->in(TypeFunc::I_O);
2394 Node* fast_mem = call->in(TypeFunc::Memory);
2395 // These two phis are pre-filled with copies of of the fast IO and Memory
2396 Node* io_phi = PhiNode::make(result_rgn, fast_io, Type::ABIO);
2397 Node* mem_phi = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2398
2399 result_rgn->init_req(2, control());
2400 io_phi ->init_req(2, i_o());
2401 mem_phi ->init_req(2, reset_memory());
2402
2403 set_all_memory( _gvn.transform(mem_phi) );
2404 set_i_o( _gvn.transform(io_phi) );
2405 }
2406
2407 set_control( _gvn.transform(result_rgn) );
2408 }
2409
2410 // Add check to deoptimize once holder klass is fully initialized.
2411 void Parse::clinit_deopt() {
2412 assert(C->has_method(), "only for normal compilations");
2413 assert(depth() == 1, "only for main compiled method");
2414 assert(is_normal_parse(), "no barrier needed on osr entry");
2415 assert(!method()->holder()->is_not_initialized(), "initialization should have been started");
2416
2417 set_parse_bci(0);
2418
2419 Node* holder = makecon(TypeKlassPtr::make(method()->holder(), Type::trust_interfaces));
2420 guard_klass_being_initialized(holder);
2421 }
2422
2423 //------------------------------return_current---------------------------------
2424 // Append current _map to _exit_return
2425 void Parse::return_current(Node* value) {
2426 if (method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2427 call_register_finalizer();
2428 }
2429
2430 // frame pointer is always same, already captured
2431 if (value != nullptr) {
2432 Node* phi = _exits.argument(0);
2433 const Type* return_type = phi->bottom_type();
2434 const TypeInstPtr* tr = return_type->isa_instptr();
2435 if ((tf()->returns_inline_type_as_fields() || (_caller->has_method() && !Compile::current()->inlining_incrementally())) &&
2436 return_type->is_inlinetypeptr()) {
2437 // Inline type is returned as fields, make sure it is scalarized
2438 if (!value->is_InlineType()) {
2439 value = InlineTypeNode::make_from_oop(this, value, return_type->inline_klass());
2440 }
2441 if (!_caller->has_method() || Compile::current()->inlining_incrementally()) {
2442 // Returning from root or an incrementally inlined method. Make sure all non-flat
2443 // fields are buffered and re-execute if allocation triggers deoptimization.
2444 PreserveReexecuteState preexecs(this);
2445 assert(tf()->returns_inline_type_as_fields(), "must be returned as fields");
2446 jvms()->set_should_reexecute(true);
2447 inc_sp(1);
2448 value = value->as_InlineType()->allocate_fields(this);
2449 }
2450 } else if (value->is_InlineType()) {
2451 // Inline type is returned as oop, make sure it is buffered and re-execute
2452 // if allocation triggers deoptimization.
2453 PreserveReexecuteState preexecs(this);
2454 jvms()->set_should_reexecute(true);
2455 inc_sp(1);
2456 value = value->as_InlineType()->buffer(this);
2457 }
2458 // ...else
2459 // If returning oops to an interface-return, there is a silent free
2460 // cast from oop to interface allowed by the Verifier. Make it explicit here.
2461 phi->add_req(value);
2462 }
2463
2464 // Do not set_parse_bci, so that return goo is credited to the return insn.
2465 set_bci(InvocationEntryBci);
2466 if (method()->is_synchronized()) {
2467 shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2468 }
2469 if (C->env()->dtrace_method_probes()) {
2470 make_dtrace_method_exit(method());
2471 }
2472
2473 SafePointNode* exit_return = _exits.map();
2474 exit_return->in( TypeFunc::Control )->add_req( control() );
2475 exit_return->in( TypeFunc::I_O )->add_req( i_o () );
2476 Node *mem = exit_return->in( TypeFunc::Memory );
2477 for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2478 if (mms.is_empty()) {
2479 // get a copy of the base memory, and patch just this one input
2480 const TypePtr* adr_type = mms.adr_type(C);
2481 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2482 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2483 gvn().set_type_bottom(phi);
2484 phi->del_req(phi->req()-1); // prepare to re-patch
2485 mms.set_memory(phi);
2486 }
2487 mms.memory()->add_req(mms.memory2());
2488 }
2489
2490 if (_first_return) {
2491 _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2492 _first_return = false;
2493 } else {
2494 _exits.map()->merge_replaced_nodes_with(map());
2495 }
2496
2497 stop_and_kill_map(); // This CFG path dies here
2498 }
2499
2500
2501 //------------------------------add_safepoint----------------------------------
2502 void Parse::add_safepoint() {
2503 uint parms = TypeFunc::Parms+1;
2504
2505 // Clear out dead values from the debug info.
2506 kill_dead_locals();
2507
2508 // Clone the JVM State
2509 SafePointNode *sfpnt = new SafePointNode(parms, nullptr);
2510
2511 // Capture memory state BEFORE a SafePoint. Since we can block at a
2512 // SafePoint we need our GC state to be safe; i.e. we need all our current
2513 // write barriers (card marks) to not float down after the SafePoint so we
2514 // must read raw memory. Likewise we need all oop stores to match the card
2515 // marks. If deopt can happen, we need ALL stores (we need the correct JVM
2516 // state on a deopt).
2517
2518 // We do not need to WRITE the memory state after a SafePoint. The control
2519 // edge will keep card-marks and oop-stores from floating up from below a
2520 // SafePoint and our true dependency added here will keep them from floating
2521 // down below a SafePoint.
2522
2523 // Clone the current memory state
2524 Node* mem = MergeMemNode::make(map()->memory());
2525
2526 mem = _gvn.transform(mem);
2527
2528 // Pass control through the safepoint
2529 sfpnt->init_req(TypeFunc::Control , control());
2530 // Fix edges normally used by a call
2531 sfpnt->init_req(TypeFunc::I_O , top() );
2532 sfpnt->init_req(TypeFunc::Memory , mem );
2533 sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2534 sfpnt->init_req(TypeFunc::FramePtr , top() );
2535
2536 // Create a node for the polling address
2537 Node *polladr;
2538 Node *thread = _gvn.transform(new ThreadLocalNode());
2539 Node *polling_page_load_addr = _gvn.transform(basic_plus_adr(top(), thread, in_bytes(JavaThread::polling_page_offset())));
2540 polladr = make_load(control(), polling_page_load_addr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
2541 sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2542
2543 // Fix up the JVM State edges
2544 add_safepoint_edges(sfpnt);
2545 Node *transformed_sfpnt = _gvn.transform(sfpnt);
2546 set_control(transformed_sfpnt);
2547
2548 // Provide an edge from root to safepoint. This makes the safepoint
2549 // appear useful until the parse has completed.
2550 if (transformed_sfpnt->is_SafePoint()) {
2551 assert(C->root() != nullptr, "Expect parse is still valid");
2552 C->root()->add_prec(transformed_sfpnt);
2553 }
2554 }
2555
2556 #ifndef PRODUCT
2557 //------------------------show_parse_info--------------------------------------
2558 void Parse::show_parse_info() {
2559 InlineTree* ilt = nullptr;
2560 if (C->ilt() != nullptr) {
2561 JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2562 ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2563 }
2564 if (PrintCompilation && Verbose) {
2565 if (depth() == 1) {
2566 if( ilt->count_inlines() ) {
2567 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2568 ilt->count_inline_bcs());
2569 tty->cr();
2570 }
2571 } else {
2572 if (method()->is_synchronized()) tty->print("s");
2573 if (method()->has_exception_handlers()) tty->print("!");
2574 // Check this is not the final compiled version
2575 if (C->trap_can_recompile()) {
2576 tty->print("-");
2577 } else {
2578 tty->print(" ");
2579 }
2580 method()->print_short_name();
2581 if (is_osr_parse()) {
2582 tty->print(" @ %d", osr_bci());
2583 }
2584 tty->print(" (%d bytes)",method()->code_size());
2585 if (ilt->count_inlines()) {
2586 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2587 ilt->count_inline_bcs());
2588 }
2589 tty->cr();
2590 }
2591 }
2592 if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2593 // Print that we succeeded; suppress this message on the first osr parse.
2594
2595 if (method()->is_synchronized()) tty->print("s");
2596 if (method()->has_exception_handlers()) tty->print("!");
2597 // Check this is not the final compiled version
2598 if (C->trap_can_recompile() && depth() == 1) {
2599 tty->print("-");
2600 } else {
2601 tty->print(" ");
2602 }
2603 if( depth() != 1 ) { tty->print(" "); } // missing compile count
2604 for (int i = 1; i < depth(); ++i) { tty->print(" "); }
2605 method()->print_short_name();
2606 if (is_osr_parse()) {
2607 tty->print(" @ %d", osr_bci());
2608 }
2609 if (ilt->caller_bci() != -1) {
2610 tty->print(" @ %d", ilt->caller_bci());
2611 }
2612 tty->print(" (%d bytes)",method()->code_size());
2613 if (ilt->count_inlines()) {
2614 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2615 ilt->count_inline_bcs());
2616 }
2617 tty->cr();
2618 }
2619 }
2620
2621
2622 //------------------------------dump-------------------------------------------
2623 // Dump information associated with the bytecodes of current _method
2624 void Parse::dump() {
2625 if( method() != nullptr ) {
2626 // Iterate over bytecodes
2627 ciBytecodeStream iter(method());
2628 for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2629 dump_bci( iter.cur_bci() );
2630 tty->cr();
2631 }
2632 }
2633 }
2634
2635 // Dump information associated with a byte code index, 'bci'
2636 void Parse::dump_bci(int bci) {
2637 // Output info on merge-points, cloning, and within _jsr..._ret
2638 // NYI
2639 tty->print(" bci:%d", bci);
2640 }
2641
2642 #endif