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