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