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