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