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()->intrinsic_id() != vmIntrinsics::_Object_init;
 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     kit.null_check_receiver_before_call(method());
1218     _caller = kit.transfer_exceptions_into_jvms();
1219     if (kit.stopped()) {
1220       _exits.add_exception_states_from(_caller);
1221       _exits.set_jvms(_caller);
1222       return nullptr;
1223     }
1224   }
1225 
1226   assert(method() != nullptr, "parser must have a method");
1227 
1228   // Create an initial safepoint to hold JVM state during parsing
1229   JVMState* jvms = new (C) JVMState(method(), _caller->has_method() ? _caller : nullptr);
1230   set_map(new SafePointNode(len, jvms));
1231   jvms->set_map(map());
1232   record_for_igvn(map());
1233   assert(jvms->endoff() == len, "correct jvms sizing");
1234 
1235   SafePointNode* inmap = _caller->map();
1236   assert(inmap != nullptr, "must have inmap");
1237   // In case of null check on receiver above
1238   map()->transfer_replaced_nodes_from(inmap, _new_idx);
1239 
1240   uint i;
1241 
1242   // Pass thru the predefined input parameters.
1243   for (i = 0; i < TypeFunc::Parms; i++) {
1244     map()->init_req(i, inmap->in(i));
1245   }
1246 
1247   if (depth() == 1) {
1248     assert(map()->memory()->Opcode() == Op_Parm, "");
1249     // Insert the memory aliasing node
1250     set_all_memory(reset_memory());
1251   }
1252   assert(merged_memory(), "");
1253 
1254   // Now add the locals which are initially bound to arguments:
1255   uint arg_size = tf()->domain_sig()->cnt();
1256   ensure_stack(arg_size - TypeFunc::Parms);  // OSR methods have funny args
1257   for (i = TypeFunc::Parms; i < arg_size; i++) {
1258     map()->init_req(i, inmap->argument(_caller, i - TypeFunc::Parms));
1259   }
1260 
1261   // Clear out the rest of the map (locals and stack)
1262   for (i = arg_size; i < len; i++) {
1263     map()->init_req(i, top());
1264   }
1265 
1266   SafePointNode* entry_map = stop();
1267   return entry_map;
1268 }
1269 
1270 //-----------------------------do_method_entry--------------------------------
1271 // Emit any code needed in the pseudo-block before BCI zero.
1272 // The main thing to do is lock the receiver of a synchronized method.
1273 void Parse::do_method_entry() {
1274   set_parse_bci(InvocationEntryBci); // Pseudo-BCP
1275   set_sp(0);                         // Java Stack Pointer
1276 
1277   NOT_PRODUCT( count_compiled_calls(true/*at_method_entry*/, false/*is_inline*/); )
1278 
1279   if (C->env()->dtrace_method_probes()) {
1280     make_dtrace_method_entry(method());
1281   }
1282 
1283 #ifdef ASSERT
1284   // Narrow receiver type when it is too broad for the method being parsed.
1285   if (!method()->is_static()) {
1286     ciInstanceKlass* callee_holder = method()->holder();
1287     const Type* holder_type = TypeInstPtr::make(TypePtr::BotPTR, callee_holder, Type::trust_interfaces);
1288 
1289     Node* receiver_obj = local(0);
1290     const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1291 
1292     if (receiver_type != nullptr && !receiver_type->higher_equal(holder_type)) {
1293       // Receiver should always be a subtype of callee holder.
1294       // But, since C2 type system doesn't properly track interfaces,
1295       // the invariant can't be expressed in the type system for default methods.
1296       // Example: for unrelated C <: I and D <: I, (C `meet` D) = Object </: I.
1297       assert(callee_holder->is_interface(), "missing subtype check");
1298 
1299       // Perform dynamic receiver subtype check against callee holder class w/ a halt on failure.
1300       Node* holder_klass = _gvn.makecon(TypeKlassPtr::make(callee_holder, Type::trust_interfaces));
1301       Node* not_subtype_ctrl = gen_subtype_check(receiver_obj, holder_klass);
1302       assert(!stopped(), "not a subtype");
1303 
1304       Node* halt = _gvn.transform(new HaltNode(not_subtype_ctrl, frameptr(), "failed receiver subtype check"));
1305       C->root()->add_req(halt);
1306     }
1307   }
1308 #endif // ASSERT
1309 
1310   // If the method is synchronized, we need to construct a lock node, attach
1311   // it to the Start node, and pin it there.
1312   if (method()->is_synchronized()) {
1313     // Insert a FastLockNode right after the Start which takes as arguments
1314     // the current thread pointer, the "this" pointer & the address of the
1315     // stack slot pair used for the lock.  The "this" pointer is a projection
1316     // off the start node, but the locking spot has to be constructed by
1317     // creating a ConLNode of 0, and boxing it with a BoxLockNode.  The BoxLockNode
1318     // becomes the second argument to the FastLockNode call.  The
1319     // FastLockNode becomes the new control parent to pin it to the start.
1320 
1321     // Setup Object Pointer
1322     Node *lock_obj = nullptr;
1323     if (method()->is_static()) {
1324       ciInstance* mirror = _method->holder()->java_mirror();
1325       const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1326       lock_obj = makecon(t_lock);
1327     } else {                  // Else pass the "this" pointer,
1328       lock_obj = local(0);    // which is Parm0 from StartNode
1329       assert(!_gvn.type(lock_obj)->make_oopptr()->can_be_inline_type(), "can't be an inline type");
1330     }
1331     // Clear out dead values from the debug info.
1332     kill_dead_locals();
1333     // Build the FastLockNode
1334     _synch_lock = shared_lock(lock_obj);
1335   }
1336 
1337   // Feed profiling data for parameters to the type system so it can
1338   // propagate it as speculative types
1339   record_profiled_parameters_for_speculation();
1340 }
1341 
1342 //------------------------------init_blocks------------------------------------
1343 // Initialize our parser map to contain the types/monitors at method entry.
1344 void Parse::init_blocks() {
1345   // Create the blocks.
1346   _block_count = flow()->block_count();
1347   _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1348 
1349   // Initialize the structs.
1350   for (int rpo = 0; rpo < block_count(); rpo++) {
1351     Block* block = rpo_at(rpo);
1352     new(block) Block(this, rpo);
1353   }
1354 
1355   // Collect predecessor and successor information.
1356   for (int rpo = 0; rpo < block_count(); rpo++) {
1357     Block* block = rpo_at(rpo);
1358     block->init_graph(this);
1359   }
1360 }
1361 
1362 //-------------------------------init_node-------------------------------------
1363 Parse::Block::Block(Parse* outer, int rpo) : _live_locals() {
1364   _flow = outer->flow()->rpo_at(rpo);
1365   _pred_count = 0;
1366   _preds_parsed = 0;
1367   _count = 0;
1368   _is_parsed = false;
1369   _is_handler = false;
1370   _has_merged_backedge = false;
1371   _start_map = nullptr;
1372   _has_predicates = false;
1373   _num_successors = 0;
1374   _all_successors = 0;
1375   _successors = nullptr;
1376   assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1377   assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1378   assert(_live_locals.size() == 0, "sanity");
1379 
1380   // entry point has additional predecessor
1381   if (flow()->is_start())  _pred_count++;
1382   assert(flow()->is_start() == (this == outer->start_block()), "");
1383 }
1384 
1385 //-------------------------------init_graph------------------------------------
1386 void Parse::Block::init_graph(Parse* outer) {
1387   // Create the successor list for this parser block.
1388   GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1389   GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1390   int ns = tfs->length();
1391   int ne = tfe->length();
1392   _num_successors = ns;
1393   _all_successors = ns+ne;
1394   _successors = (ns+ne == 0) ? nullptr : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1395   int p = 0;
1396   for (int i = 0; i < ns+ne; i++) {
1397     ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1398     Block* block2 = outer->rpo_at(tf2->rpo());
1399     _successors[i] = block2;
1400 
1401     // Accumulate pred info for the other block, too.
1402     // Note: We also need to set _pred_count for exception blocks since they could
1403     // also have normal predecessors (reached without athrow by an explicit jump).
1404     // This also means that next_path_num can be called along exception paths.
1405     block2->_pred_count++;
1406     if (i >= ns) {
1407       block2->_is_handler = true;
1408     }
1409 
1410     #ifdef ASSERT
1411     // A block's successors must be distinguishable by BCI.
1412     // That is, no bytecode is allowed to branch to two different
1413     // clones of the same code location.
1414     for (int j = 0; j < i; j++) {
1415       Block* block1 = _successors[j];
1416       if (block1 == block2)  continue;  // duplicates are OK
1417       assert(block1->start() != block2->start(), "successors have unique bcis");
1418     }
1419     #endif
1420   }
1421 }
1422 
1423 //---------------------------successor_for_bci---------------------------------
1424 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1425   for (int i = 0; i < all_successors(); i++) {
1426     Block* block2 = successor_at(i);
1427     if (block2->start() == bci)  return block2;
1428   }
1429   // We can actually reach here if ciTypeFlow traps out a block
1430   // due to an unloaded class, and concurrently with compilation the
1431   // class is then loaded, so that a later phase of the parser is
1432   // able to see more of the bytecode CFG.  Or, the flow pass and
1433   // the parser can have a minor difference of opinion about executability
1434   // of bytecodes.  For example, "obj.field = null" is executable even
1435   // if the field's type is an unloaded class; the flow pass used to
1436   // make a trap for such code.
1437   return nullptr;
1438 }
1439 
1440 
1441 //-----------------------------stack_type_at-----------------------------------
1442 const Type* Parse::Block::stack_type_at(int i) const {
1443   return get_type(flow()->stack_type_at(i));
1444 }
1445 
1446 
1447 //-----------------------------local_type_at-----------------------------------
1448 const Type* Parse::Block::local_type_at(int i) const {
1449   // Make dead locals fall to bottom.
1450   if (_live_locals.size() == 0) {
1451     MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1452     // This bitmap can be zero length if we saw a breakpoint.
1453     // In such cases, pretend they are all live.
1454     ((Block*)this)->_live_locals = live_locals;
1455   }
1456   if (_live_locals.size() > 0 && !_live_locals.at(i))
1457     return Type::BOTTOM;
1458 
1459   return get_type(flow()->local_type_at(i));
1460 }
1461 
1462 
1463 #ifndef PRODUCT
1464 
1465 //----------------------------name_for_bc--------------------------------------
1466 // helper method for BytecodeParseHistogram
1467 static const char* name_for_bc(int i) {
1468   return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1469 }
1470 
1471 //----------------------------BytecodeParseHistogram------------------------------------
1472 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1473   _parser   = p;
1474   _compiler = c;
1475   if( ! _initialized ) { _initialized = true; reset(); }
1476 }
1477 
1478 //----------------------------current_count------------------------------------
1479 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1480   switch( bph_type ) {
1481   case BPH_transforms: { return _parser->gvn().made_progress(); }
1482   case BPH_values:     { return _parser->gvn().made_new_values(); }
1483   default: { ShouldNotReachHere(); return 0; }
1484   }
1485 }
1486 
1487 //----------------------------initialized--------------------------------------
1488 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1489 
1490 //----------------------------reset--------------------------------------------
1491 void Parse::BytecodeParseHistogram::reset() {
1492   int i = Bytecodes::number_of_codes;
1493   while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1494 }
1495 
1496 //----------------------------set_initial_state--------------------------------
1497 // Record info when starting to parse one bytecode
1498 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1499   if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1500     _initial_bytecode    = bc;
1501     _initial_node_count  = _compiler->unique();
1502     _initial_transforms  = current_count(BPH_transforms);
1503     _initial_values      = current_count(BPH_values);
1504   }
1505 }
1506 
1507 //----------------------------record_change--------------------------------
1508 // Record results of parsing one bytecode
1509 void Parse::BytecodeParseHistogram::record_change() {
1510   if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1511     ++_bytecodes_parsed[_initial_bytecode];
1512     _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1513     _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1514     _new_values        [_initial_bytecode] += (current_count(BPH_values)     - _initial_values);
1515   }
1516 }
1517 
1518 
1519 //----------------------------print--------------------------------------------
1520 void Parse::BytecodeParseHistogram::print(float cutoff) {
1521   ResourceMark rm;
1522   // print profile
1523   int total  = 0;
1524   int i      = 0;
1525   for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1526   int abs_sum = 0;
1527   tty->cr();   //0123456789012345678901234567890123456789012345678901234567890123456789
1528   tty->print_cr("Histogram of %d parsed bytecodes:", total);
1529   if( total == 0 ) { return; }
1530   tty->cr();
1531   tty->print_cr("absolute:  count of compiled bytecodes of this type");
1532   tty->print_cr("relative:  percentage contribution to compiled nodes");
1533   tty->print_cr("nodes   :  Average number of nodes constructed per bytecode");
1534   tty->print_cr("rnodes  :  Significance towards total nodes constructed, (nodes*relative)");
1535   tty->print_cr("transforms: Average amount of transform progress per bytecode compiled");
1536   tty->print_cr("values  :  Average number of node values improved per bytecode");
1537   tty->print_cr("name    :  Bytecode name");
1538   tty->cr();
1539   tty->print_cr("  absolute  relative   nodes  rnodes  transforms  values   name");
1540   tty->print_cr("----------------------------------------------------------------------");
1541   while (--i > 0) {
1542     int       abs = _bytecodes_parsed[i];
1543     float     rel = abs * 100.0F / total;
1544     float   nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1545     float  rnodes = _bytecodes_parsed[i] == 0 ? 0 :  rel * nodes;
1546     float  xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1547     float  values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values       [i])/_bytecodes_parsed[i];
1548     if (cutoff <= rel) {
1549       tty->print_cr("%10d  %7.2f%%  %6.1f  %6.2f   %6.1f   %6.1f     %s", abs, rel, nodes, rnodes, xforms, values, name_for_bc(i));
1550       abs_sum += abs;
1551     }
1552   }
1553   tty->print_cr("----------------------------------------------------------------------");
1554   float rel_sum = abs_sum * 100.0F / total;
1555   tty->print_cr("%10d  %7.2f%%    (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1556   tty->print_cr("----------------------------------------------------------------------");
1557   tty->cr();
1558 }
1559 #endif
1560 
1561 //----------------------------load_state_from----------------------------------
1562 // Load block/map/sp.  But not do not touch iter/bci.
1563 void Parse::load_state_from(Block* block) {
1564   set_block(block);
1565   // load the block's JVM state:
1566   set_map(block->start_map());
1567   set_sp( block->start_sp());
1568 }
1569 
1570 
1571 //-----------------------------record_state------------------------------------
1572 void Parse::Block::record_state(Parse* p) {
1573   assert(!is_merged(), "can only record state once, on 1st inflow");
1574   assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1575   set_start_map(p->stop());
1576 }
1577 
1578 
1579 //------------------------------do_one_block-----------------------------------
1580 void Parse::do_one_block() {
1581   if (TraceOptoParse) {
1582     Block *b = block();
1583     int ns = b->num_successors();
1584     int nt = b->all_successors();
1585 
1586     tty->print("Parsing block #%d at bci [%d,%d), successors: ",
1587                   block()->rpo(), block()->start(), block()->limit());
1588     for (int i = 0; i < nt; i++) {
1589       tty->print((( i < ns) ? " %d" : " %d(e)"), b->successor_at(i)->rpo());
1590     }
1591     if (b->is_loop_head()) {
1592       tty->print("  lphd");
1593     }
1594     if (b->is_irreducible_loop_entry()) {
1595       tty->print("  irreducible");
1596     }
1597     tty->cr();
1598   }
1599 
1600   assert(block()->is_merged(), "must be merged before being parsed");
1601   block()->mark_parsed();
1602 
1603   // Set iterator to start of block.
1604   iter().reset_to_bci(block()->start());
1605 
1606   CompileLog* log = C->log();
1607 
1608   // Parse bytecodes
1609   while (!stopped() && !failing()) {
1610     iter().next();
1611 
1612     // Learn the current bci from the iterator:
1613     set_parse_bci(iter().cur_bci());
1614 
1615     if (bci() == block()->limit()) {
1616       // Do not walk into the next block until directed by do_all_blocks.
1617       merge(bci());
1618       break;
1619     }
1620     assert(bci() < block()->limit(), "bci still in block");
1621 
1622     if (log != nullptr) {
1623       // Output an optional context marker, to help place actions
1624       // that occur during parsing of this BC.  If there is no log
1625       // output until the next context string, this context string
1626       // will be silently ignored.
1627       log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1628     }
1629 
1630     if (block()->has_trap_at(bci())) {
1631       // We must respect the flow pass's traps, because it will refuse
1632       // to produce successors for trapping blocks.
1633       int trap_index = block()->flow()->trap_index();
1634       assert(trap_index != 0, "trap index must be valid");
1635       uncommon_trap(trap_index);
1636       break;
1637     }
1638 
1639     NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1640 
1641 #ifdef ASSERT
1642     int pre_bc_sp = sp();
1643     int inputs, depth;
1644     bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1645     assert(!have_se || pre_bc_sp >= inputs, "have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs);
1646 #endif //ASSERT
1647 
1648     do_one_bytecode();
1649     if (failing()) return;
1650 
1651     assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1652            "incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth);
1653 
1654     do_exceptions();
1655 
1656     NOT_PRODUCT( parse_histogram()->record_change(); );
1657 
1658     if (log != nullptr)
1659       log->clear_context();  // skip marker if nothing was printed
1660 
1661     // Fall into next bytecode.  Each bytecode normally has 1 sequential
1662     // successor which is typically made ready by visiting this bytecode.
1663     // If the successor has several predecessors, then it is a merge
1664     // point, starts a new basic block, and is handled like other basic blocks.
1665   }
1666 }
1667 
1668 
1669 //------------------------------merge------------------------------------------
1670 void Parse::set_parse_bci(int bci) {
1671   set_bci(bci);
1672   Node_Notes* nn = C->default_node_notes();
1673   if (nn == nullptr)  return;
1674 
1675   // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1676   if (!DebugInlinedCalls && depth() > 1) {
1677     return;
1678   }
1679 
1680   // Update the JVMS annotation, if present.
1681   JVMState* jvms = nn->jvms();
1682   if (jvms != nullptr && jvms->bci() != bci) {
1683     // Update the JVMS.
1684     jvms = jvms->clone_shallow(C);
1685     jvms->set_bci(bci);
1686     nn->set_jvms(jvms);
1687   }
1688 }
1689 
1690 //------------------------------merge------------------------------------------
1691 // Merge the current mapping into the basic block starting at bci
1692 void Parse::merge(int target_bci) {
1693   Block* target = successor_for_bci(target_bci);
1694   if (target == nullptr) { handle_missing_successor(target_bci); return; }
1695   assert(!target->is_ready(), "our arrival must be expected");
1696   int pnum = target->next_path_num();
1697   merge_common(target, pnum);
1698 }
1699 
1700 //-------------------------merge_new_path--------------------------------------
1701 // Merge the current mapping into the basic block, using a new path
1702 void Parse::merge_new_path(int target_bci) {
1703   Block* target = successor_for_bci(target_bci);
1704   if (target == nullptr) { handle_missing_successor(target_bci); return; }
1705   assert(!target->is_ready(), "new path into frozen graph");
1706   int pnum = target->add_new_path();
1707   merge_common(target, pnum);
1708 }
1709 
1710 //-------------------------merge_exception-------------------------------------
1711 // Merge the current mapping into the basic block starting at bci
1712 // The ex_oop must be pushed on the stack, unlike throw_to_exit.
1713 void Parse::merge_exception(int target_bci) {
1714 #ifdef ASSERT
1715   if (target_bci < bci()) {
1716     C->set_exception_backedge();
1717   }
1718 #endif
1719   assert(sp() == 1, "must have only the throw exception on the stack");
1720   Block* target = successor_for_bci(target_bci);
1721   if (target == nullptr) { handle_missing_successor(target_bci); return; }
1722   assert(target->is_handler(), "exceptions are handled by special blocks");
1723   int pnum = target->add_new_path();
1724   merge_common(target, pnum);
1725 }
1726 
1727 //--------------------handle_missing_successor---------------------------------
1728 void Parse::handle_missing_successor(int target_bci) {
1729 #ifndef PRODUCT
1730   Block* b = block();
1731   int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1732   tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1733 #endif
1734   ShouldNotReachHere();
1735 }
1736 
1737 //--------------------------merge_common---------------------------------------
1738 void Parse::merge_common(Parse::Block* target, int pnum) {
1739   if (TraceOptoParse) {
1740     tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1741   }
1742 
1743   // Zap extra stack slots to top
1744   assert(sp() == target->start_sp(), "");
1745   clean_stack(sp());
1746 
1747   // Check for merge conflicts involving inline types
1748   JVMState* old_jvms = map()->jvms();
1749   int old_bci = bci();
1750   JVMState* tmp_jvms = old_jvms->clone_shallow(C);
1751   tmp_jvms->set_should_reexecute(true);
1752   tmp_jvms->bind_map(map());
1753   // Execution needs to restart a the next bytecode (entry of next
1754   // block)
1755   if (target->is_merged() ||
1756       pnum > PhiNode::Input ||
1757       target->is_handler() ||
1758       target->is_loop_head()) {
1759     set_parse_bci(target->start());
1760     for (uint j = TypeFunc::Parms; j < map()->req(); j++) {
1761       Node* n = map()->in(j);                 // Incoming change to target state.
1762       const Type* t = nullptr;
1763       if (tmp_jvms->is_loc(j)) {
1764         t = target->local_type_at(j - tmp_jvms->locoff());
1765       } else if (tmp_jvms->is_stk(j) && j < (uint)sp() + tmp_jvms->stkoff()) {
1766         t = target->stack_type_at(j - tmp_jvms->stkoff());
1767       }
1768       if (t != nullptr && t != Type::BOTTOM) {
1769         if (n->is_InlineType() && !t->is_inlinetypeptr()) {
1770           // Allocate inline type in src block to be able to merge it with oop in target block
1771           map()->set_req(j, n->as_InlineType()->buffer(this));
1772         } else if (!n->is_InlineType() && t->is_inlinetypeptr()) {
1773           // Scalarize null in src block to be able to merge it with inline type in target block
1774           assert(gvn().type(n)->is_zero_type(), "Should have been scalarized");
1775           map()->set_req(j, InlineTypeNode::make_null(gvn(), t->inline_klass()));
1776         }
1777       }
1778     }
1779   }
1780   old_jvms->bind_map(map());
1781   set_parse_bci(old_bci);
1782 
1783   if (!target->is_merged()) {   // No prior mapping at this bci
1784     if (TraceOptoParse) { tty->print(" with empty state");  }
1785 
1786     // If this path is dead, do not bother capturing it as a merge.
1787     // It is "as if" we had 1 fewer predecessors from the beginning.
1788     if (stopped()) {
1789       if (TraceOptoParse)  tty->print_cr(", but path is dead and doesn't count");
1790       return;
1791     }
1792 
1793     // Make a region if we know there are multiple or unpredictable inputs.
1794     // (Also, if this is a plain fall-through, we might see another region,
1795     // which must not be allowed into this block's map.)
1796     if (pnum > PhiNode::Input         // Known multiple inputs.
1797         || target->is_handler()       // These have unpredictable inputs.
1798         || target->is_loop_head()     // Known multiple inputs
1799         || control()->is_Region()) {  // We must hide this guy.
1800 
1801       int current_bci = bci();
1802       set_parse_bci(target->start()); // Set target bci
1803       if (target->is_SEL_head()) {
1804         DEBUG_ONLY( target->mark_merged_backedge(block()); )
1805         if (target->start() == 0) {
1806           // Add Parse Predicates for the special case when
1807           // there are backbranches to the method entry.
1808           add_parse_predicates();
1809         }
1810       }
1811       // Add a Region to start the new basic block.  Phis will be added
1812       // later lazily.
1813       int edges = target->pred_count();
1814       if (edges < pnum)  edges = pnum;  // might be a new path!
1815       RegionNode *r = new RegionNode(edges+1);
1816       gvn().set_type(r, Type::CONTROL);
1817       record_for_igvn(r);
1818       // zap all inputs to null for debugging (done in Node(uint) constructor)
1819       // for (int j = 1; j < edges+1; j++) { r->init_req(j, nullptr); }
1820       r->init_req(pnum, control());
1821       set_control(r);
1822       target->copy_irreducible_status_to(r, jvms());
1823       set_parse_bci(current_bci); // Restore bci
1824     }
1825 
1826     // Convert the existing Parser mapping into a mapping at this bci.
1827     store_state_to(target);
1828     assert(target->is_merged(), "do not come here twice");
1829 
1830   } else {                      // Prior mapping at this bci
1831     if (TraceOptoParse) {  tty->print(" with previous state"); }
1832 #ifdef ASSERT
1833     if (target->is_SEL_head()) {
1834       target->mark_merged_backedge(block());
1835     }
1836 #endif
1837 
1838     // We must not manufacture more phis if the target is already parsed.
1839     bool nophi = target->is_parsed();
1840 
1841     SafePointNode* newin = map();// Hang on to incoming mapping
1842     Block* save_block = block(); // Hang on to incoming block;
1843     load_state_from(target);    // Get prior mapping
1844 
1845     assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
1846     assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
1847     assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
1848     assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
1849 
1850     // Iterate over my current mapping and the old mapping.
1851     // Where different, insert Phi functions.
1852     // Use any existing Phi functions.
1853     assert(control()->is_Region(), "must be merging to a region");
1854     RegionNode* r = control()->as_Region();
1855 
1856     // Compute where to merge into
1857     // Merge incoming control path
1858     r->init_req(pnum, newin->control());
1859 
1860     if (pnum == 1) {            // Last merge for this Region?
1861       if (!block()->flow()->is_irreducible_loop_secondary_entry()) {
1862         Node* result = _gvn.transform_no_reclaim(r);
1863         if (r != result && TraceOptoParse) {
1864           tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
1865         }
1866       }
1867       record_for_igvn(r);
1868     }
1869 
1870     // Update all the non-control inputs to map:
1871     assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
1872     bool check_elide_phi = target->is_SEL_backedge(save_block);
1873     bool last_merge = (pnum == PhiNode::Input);
1874     for (uint j = 1; j < newin->req(); j++) {
1875       Node* m = map()->in(j);   // Current state of target.
1876       Node* n = newin->in(j);   // Incoming change to target state.
1877       PhiNode* phi;
1878       if (m->is_Phi() && m->as_Phi()->region() == r) {
1879         phi = m->as_Phi();
1880       } else if (m->is_InlineType() && m->as_InlineType()->has_phi_inputs(r)) {
1881         phi = m->as_InlineType()->get_oop()->as_Phi();
1882       } else {
1883         phi = nullptr;
1884       }
1885       if (m != n) {             // Different; must merge
1886         switch (j) {
1887         // Frame pointer and Return Address never changes
1888         case TypeFunc::FramePtr:// Drop m, use the original value
1889         case TypeFunc::ReturnAdr:
1890           break;
1891         case TypeFunc::Memory:  // Merge inputs to the MergeMem node
1892           assert(phi == nullptr, "the merge contains phis, not vice versa");
1893           merge_memory_edges(n->as_MergeMem(), pnum, nophi);
1894           continue;
1895         default:                // All normal stuff
1896           if (phi == nullptr) {
1897             const JVMState* jvms = map()->jvms();
1898             if (EliminateNestedLocks &&
1899                 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
1900               // BoxLock nodes are not commoning.
1901               // Use old BoxLock node as merged box.
1902               assert(newin->jvms()->is_monitor_box(j), "sanity");
1903               // This assert also tests that nodes are BoxLock.
1904               assert(BoxLockNode::same_slot(n, m), "sanity");
1905               C->gvn_replace_by(n, m);
1906             } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
1907               phi = ensure_phi(j, nophi);
1908             }
1909           }
1910           break;
1911         }
1912       }
1913       // At this point, n might be top if:
1914       //  - there is no phi (because TypeFlow detected a conflict), or
1915       //  - the corresponding control edges is top (a dead incoming path)
1916       // It is a bug if we create a phi which sees a garbage value on a live path.
1917 
1918       // Merging two inline types?
1919       if (phi != nullptr && phi->bottom_type()->is_inlinetypeptr()) {
1920         // Reload current state because it may have been updated by ensure_phi
1921         m = map()->in(j);
1922         InlineTypeNode* vtm = m->as_InlineType(); // Current inline type
1923         InlineTypeNode* vtn = n->as_InlineType(); // Incoming inline type
1924         assert(vtm->get_oop() == phi, "Inline type should have Phi input");
1925         if (TraceOptoParse) {
1926 #ifdef ASSERT
1927           tty->print_cr("\nMerging inline types");
1928           tty->print_cr("Current:");
1929           vtm->dump(2);
1930           tty->print_cr("Incoming:");
1931           vtn->dump(2);
1932           tty->cr();
1933 #endif
1934         }
1935         // Do the merge
1936         vtm->merge_with(&_gvn, vtn, pnum, last_merge);
1937         if (last_merge) {
1938           map()->set_req(j, _gvn.transform_no_reclaim(vtm));
1939           record_for_igvn(vtm);
1940         }
1941       } else if (phi != nullptr) {
1942         assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
1943         assert(phi->region() == r, "");
1944         phi->set_req(pnum, n);  // Then add 'n' to the merge
1945         if (last_merge) {
1946           // Last merge for this Phi.
1947           // So far, Phis have had a reasonable type from ciTypeFlow.
1948           // Now _gvn will join that with the meet of current inputs.
1949           // BOTTOM is never permissible here, 'cause pessimistically
1950           // Phis of pointers cannot lose the basic pointer type.
1951           debug_only(const Type* bt1 = phi->bottom_type());
1952           assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
1953           map()->set_req(j, _gvn.transform_no_reclaim(phi));
1954           debug_only(const Type* bt2 = phi->bottom_type());
1955           assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
1956           record_for_igvn(phi);
1957         }
1958       }
1959     } // End of for all values to be merged
1960 
1961     if (last_merge && !r->in(0)) {         // The occasional useless Region
1962       assert(control() == r, "");
1963       set_control(r->nonnull_req());
1964     }
1965 
1966     map()->merge_replaced_nodes_with(newin);
1967 
1968     // newin has been subsumed into the lazy merge, and is now dead.
1969     set_block(save_block);
1970 
1971     stop();                     // done with this guy, for now
1972   }
1973 
1974   if (TraceOptoParse) {
1975     tty->print_cr(" on path %d", pnum);
1976   }
1977 
1978   // Done with this parser state.
1979   assert(stopped(), "");
1980 }
1981 
1982 
1983 //--------------------------merge_memory_edges---------------------------------
1984 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
1985   // (nophi means we must not create phis, because we already parsed here)
1986   assert(n != nullptr, "");
1987   // Merge the inputs to the MergeMems
1988   MergeMemNode* m = merged_memory();
1989 
1990   assert(control()->is_Region(), "must be merging to a region");
1991   RegionNode* r = control()->as_Region();
1992 
1993   PhiNode* base = nullptr;
1994   MergeMemNode* remerge = nullptr;
1995   for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
1996     Node *p = mms.force_memory();
1997     Node *q = mms.memory2();
1998     if (mms.is_empty() && nophi) {
1999       // Trouble:  No new splits allowed after a loop body is parsed.
2000       // Instead, wire the new split into a MergeMem on the backedge.
2001       // The optimizer will sort it out, slicing the phi.
2002       if (remerge == nullptr) {
2003         guarantee(base != nullptr, "");
2004         assert(base->in(0) != nullptr, "should not be xformed away");
2005         remerge = MergeMemNode::make(base->in(pnum));
2006         gvn().set_type(remerge, Type::MEMORY);
2007         base->set_req(pnum, remerge);
2008       }
2009       remerge->set_memory_at(mms.alias_idx(), q);
2010       continue;
2011     }
2012     assert(!q->is_MergeMem(), "");
2013     PhiNode* phi;
2014     if (p != q) {
2015       phi = ensure_memory_phi(mms.alias_idx(), nophi);
2016     } else {
2017       if (p->is_Phi() && p->as_Phi()->region() == r)
2018         phi = p->as_Phi();
2019       else
2020         phi = nullptr;
2021     }
2022     // Insert q into local phi
2023     if (phi != nullptr) {
2024       assert(phi->region() == r, "");
2025       p = phi;
2026       phi->set_req(pnum, q);
2027       if (mms.at_base_memory()) {
2028         base = phi;  // delay transforming it
2029       } else if (pnum == 1) {
2030         record_for_igvn(phi);
2031         p = _gvn.transform_no_reclaim(phi);
2032       }
2033       mms.set_memory(p);// store back through the iterator
2034     }
2035   }
2036   // Transform base last, in case we must fiddle with remerging.
2037   if (base != nullptr && pnum == 1) {
2038     record_for_igvn(base);
2039     m->set_base_memory( _gvn.transform_no_reclaim(base) );
2040   }
2041 }
2042 
2043 
2044 //------------------------ensure_phis_everywhere-------------------------------
2045 void Parse::ensure_phis_everywhere() {
2046   ensure_phi(TypeFunc::I_O);
2047 
2048   // Ensure a phi on all currently known memories.
2049   for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
2050     ensure_memory_phi(mms.alias_idx());
2051     debug_only(mms.set_memory());  // keep the iterator happy
2052   }
2053 
2054   // Note:  This is our only chance to create phis for memory slices.
2055   // If we miss a slice that crops up later, it will have to be
2056   // merged into the base-memory phi that we are building here.
2057   // Later, the optimizer will comb out the knot, and build separate
2058   // phi-loops for each memory slice that matters.
2059 
2060   // Monitors must nest nicely and not get confused amongst themselves.
2061   // Phi-ify everything up to the monitors, though.
2062   uint monoff = map()->jvms()->monoff();
2063   uint nof_monitors = map()->jvms()->nof_monitors();
2064 
2065   assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
2066   bool check_elide_phi = block()->is_SEL_head();
2067   for (uint i = TypeFunc::Parms; i < monoff; i++) {
2068     if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
2069       ensure_phi(i);
2070     }
2071   }
2072 
2073   // Even monitors need Phis, though they are well-structured.
2074   // This is true for OSR methods, and also for the rare cases where
2075   // a monitor object is the subject of a replace_in_map operation.
2076   // See bugs 4426707 and 5043395.
2077   for (uint m = 0; m < nof_monitors; m++) {
2078     ensure_phi(map()->jvms()->monitor_obj_offset(m));
2079   }
2080 }
2081 
2082 
2083 //-----------------------------add_new_path------------------------------------
2084 // Add a previously unaccounted predecessor to this block.
2085 int Parse::Block::add_new_path() {
2086   // If there is no map, return the lowest unused path number.
2087   if (!is_merged())  return pred_count()+1;  // there will be a map shortly
2088 
2089   SafePointNode* map = start_map();
2090   if (!map->control()->is_Region())
2091     return pred_count()+1;  // there may be a region some day
2092   RegionNode* r = map->control()->as_Region();
2093 
2094   // Add new path to the region.
2095   uint pnum = r->req();
2096   r->add_req(nullptr);
2097 
2098   for (uint i = 1; i < map->req(); i++) {
2099     Node* n = map->in(i);
2100     if (i == TypeFunc::Memory) {
2101       // Ensure a phi on all currently known memories.
2102       for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
2103         Node* phi = mms.memory();
2104         if (phi->is_Phi() && phi->as_Phi()->region() == r) {
2105           assert(phi->req() == pnum, "must be same size as region");
2106           phi->add_req(nullptr);
2107         }
2108       }
2109     } else {
2110       if (n->is_Phi() && n->as_Phi()->region() == r) {
2111         assert(n->req() == pnum, "must be same size as region");
2112         n->add_req(nullptr);
2113       } else if (n->is_InlineType() && n->as_InlineType()->has_phi_inputs(r)) {
2114         n->as_InlineType()->add_new_path(r);
2115       }
2116     }
2117   }
2118 
2119   return pnum;
2120 }
2121 
2122 //------------------------------ensure_phi-------------------------------------
2123 // Turn the idx'th entry of the current map into a Phi
2124 PhiNode *Parse::ensure_phi(int idx, bool nocreate) {
2125   SafePointNode* map = this->map();
2126   Node* region = map->control();
2127   assert(region->is_Region(), "");
2128 
2129   Node* o = map->in(idx);
2130   assert(o != nullptr, "");
2131 
2132   if (o == top())  return nullptr; // TOP always merges into TOP
2133 
2134   if (o->is_Phi() && o->as_Phi()->region() == region) {
2135     return o->as_Phi();
2136   }
2137   InlineTypeNode* vt = o->isa_InlineType();
2138   if (vt != nullptr && vt->has_phi_inputs(region)) {
2139     return vt->get_oop()->as_Phi();
2140   }
2141 
2142   // Now use a Phi here for merging
2143   assert(!nocreate, "Cannot build a phi for a block already parsed.");
2144   const JVMState* jvms = map->jvms();
2145   const Type* t = nullptr;
2146   if (jvms->is_loc(idx)) {
2147     t = block()->local_type_at(idx - jvms->locoff());
2148   } else if (jvms->is_stk(idx)) {
2149     t = block()->stack_type_at(idx - jvms->stkoff());
2150   } else if (jvms->is_mon(idx)) {
2151     assert(!jvms->is_monitor_box(idx), "no phis for boxes");
2152     t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
2153   } else if ((uint)idx < TypeFunc::Parms) {
2154     t = o->bottom_type();  // Type::RETURN_ADDRESS or such-like.
2155   } else {
2156     assert(false, "no type information for this phi");
2157   }
2158 
2159   // If the type falls to bottom, then this must be a local that
2160   // is already dead or is mixing ints and oops or some such.
2161   // Forcing it to top makes it go dead.
2162   if (t == Type::BOTTOM) {
2163     map->set_req(idx, top());
2164     return nullptr;
2165   }
2166 
2167   // Do not create phis for top either.
2168   // A top on a non-null control flow must be an unused even after the.phi.
2169   if (t == Type::TOP || t == Type::HALF) {
2170     map->set_req(idx, top());
2171     return nullptr;
2172   }
2173 
2174   if (vt != nullptr && t->is_inlinetypeptr()) {
2175     // Inline types are merged by merging their field values.
2176     // Create a cloned InlineTypeNode with phi inputs that
2177     // represents the merged inline type and update the map.
2178     vt = vt->clone_with_phis(&_gvn, region);
2179     map->set_req(idx, vt);
2180     return vt->get_oop()->as_Phi();
2181   } else {
2182     PhiNode* phi = PhiNode::make(region, o, t);
2183     gvn().set_type(phi, t);
2184     if (C->do_escape_analysis()) record_for_igvn(phi);
2185     map->set_req(idx, phi);
2186     return phi;
2187   }
2188 }
2189 
2190 //--------------------------ensure_memory_phi----------------------------------
2191 // Turn the idx'th slice of the current memory into a Phi
2192 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
2193   MergeMemNode* mem = merged_memory();
2194   Node* region = control();
2195   assert(region->is_Region(), "");
2196 
2197   Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
2198   assert(o != nullptr && o != top(), "");
2199 
2200   PhiNode* phi;
2201   if (o->is_Phi() && o->as_Phi()->region() == region) {
2202     phi = o->as_Phi();
2203     if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
2204       // clone the shared base memory phi to make a new memory split
2205       assert(!nocreate, "Cannot build a phi for a block already parsed.");
2206       const Type* t = phi->bottom_type();
2207       const TypePtr* adr_type = C->get_adr_type(idx);
2208       phi = phi->slice_memory(adr_type);
2209       gvn().set_type(phi, t);
2210     }
2211     return phi;
2212   }
2213 
2214   // Now use a Phi here for merging
2215   assert(!nocreate, "Cannot build a phi for a block already parsed.");
2216   const Type* t = o->bottom_type();
2217   const TypePtr* adr_type = C->get_adr_type(idx);
2218   phi = PhiNode::make(region, o, t, adr_type);
2219   gvn().set_type(phi, t);
2220   if (idx == Compile::AliasIdxBot)
2221     mem->set_base_memory(phi);
2222   else
2223     mem->set_memory_at(idx, phi);
2224   return phi;
2225 }
2226 
2227 //------------------------------call_register_finalizer-----------------------
2228 // Check the klass of the receiver and call register_finalizer if the
2229 // class need finalization.
2230 void Parse::call_register_finalizer() {
2231   Node* receiver = local(0);
2232   assert(receiver != nullptr && receiver->bottom_type()->isa_instptr() != nullptr,
2233          "must have non-null instance type");
2234 
2235   const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
2236   if (tinst != nullptr && tinst->is_loaded() && !tinst->klass_is_exact()) {
2237     // The type isn't known exactly so see if CHA tells us anything.
2238     ciInstanceKlass* ik = tinst->instance_klass();
2239     if (!Dependencies::has_finalizable_subclass(ik)) {
2240       // No finalizable subclasses so skip the dynamic check.
2241       C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2242       return;
2243     }
2244   }
2245 
2246   // Insert a dynamic test for whether the instance needs
2247   // finalization.  In general this will fold up since the concrete
2248   // class is often visible so the access flags are constant.
2249   Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2250   Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, nullptr, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2251 
2252   Node* access_flags_addr = basic_plus_adr(klass, klass, in_bytes(Klass::access_flags_offset()));
2253   Node* access_flags = make_load(nullptr, access_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
2254 
2255   Node* mask  = _gvn.transform(new AndINode(access_flags, intcon(JVM_ACC_HAS_FINALIZER)));
2256   Node* check = _gvn.transform(new CmpINode(mask, intcon(0)));
2257   Node* test  = _gvn.transform(new BoolNode(check, BoolTest::ne));
2258 
2259   IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2260 
2261   RegionNode* result_rgn = new RegionNode(3);
2262   record_for_igvn(result_rgn);
2263 
2264   Node *skip_register = _gvn.transform(new IfFalseNode(iff));
2265   result_rgn->init_req(1, skip_register);
2266 
2267   Node *needs_register = _gvn.transform(new IfTrueNode(iff));
2268   set_control(needs_register);
2269   if (stopped()) {
2270     // There is no slow path.
2271     result_rgn->init_req(2, top());
2272   } else {
2273     Node *call = make_runtime_call(RC_NO_LEAF,
2274                                    OptoRuntime::register_finalizer_Type(),
2275                                    OptoRuntime::register_finalizer_Java(),
2276                                    nullptr, TypePtr::BOTTOM,
2277                                    receiver);
2278     make_slow_call_ex(call, env()->Throwable_klass(), true);
2279 
2280     Node* fast_io  = call->in(TypeFunc::I_O);
2281     Node* fast_mem = call->in(TypeFunc::Memory);
2282     // These two phis are pre-filled with copies of of the fast IO and Memory
2283     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
2284     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2285 
2286     result_rgn->init_req(2, control());
2287     io_phi    ->init_req(2, i_o());
2288     mem_phi   ->init_req(2, reset_memory());
2289 
2290     set_all_memory( _gvn.transform(mem_phi) );
2291     set_i_o(        _gvn.transform(io_phi) );
2292   }
2293 
2294   set_control( _gvn.transform(result_rgn) );
2295 }
2296 
2297 // Add check to deoptimize once holder klass is fully initialized.
2298 void Parse::clinit_deopt() {
2299   assert(C->has_method(), "only for normal compilations");
2300   assert(depth() == 1, "only for main compiled method");
2301   assert(is_normal_parse(), "no barrier needed on osr entry");
2302   assert(!method()->holder()->is_not_initialized(), "initialization should have been started");
2303 
2304   set_parse_bci(0);
2305 
2306   Node* holder = makecon(TypeKlassPtr::make(method()->holder(), Type::trust_interfaces));
2307   guard_klass_being_initialized(holder);
2308 }
2309 
2310 // Add check to deoptimize if RTM state is not ProfileRTM
2311 void Parse::rtm_deopt() {
2312 #if INCLUDE_RTM_OPT
2313   if (C->profile_rtm()) {
2314     assert(C->has_method(), "only for normal compilations");
2315     assert(!C->method()->method_data()->is_empty(), "MDO is needed to record RTM state");
2316     assert(depth() == 1, "generate check only for main compiled method");
2317 
2318     // Set starting bci for uncommon trap.
2319     set_parse_bci(is_osr_parse() ? osr_bci() : 0);
2320 
2321     // Load the rtm_state from the MethodData.
2322     const TypePtr* adr_type = TypeMetadataPtr::make(C->method()->method_data());
2323     Node* mdo = makecon(adr_type);
2324     int offset = in_bytes(MethodData::rtm_state_offset());
2325     Node* adr_node = basic_plus_adr(mdo, mdo, offset);
2326     Node* rtm_state = make_load(control(), adr_node, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
2327 
2328     // Separate Load from Cmp by Opaque.
2329     // In expand_macro_nodes() it will be replaced either
2330     // with this load when there are locks in the code
2331     // or with ProfileRTM (cmp->in(2)) otherwise so that
2332     // the check will fold.
2333     Node* profile_state = makecon(TypeInt::make(ProfileRTM));
2334     Node* opq   = _gvn.transform( new Opaque3Node(C, rtm_state, Opaque3Node::RTM_OPT) );
2335     Node* chk   = _gvn.transform( new CmpINode(opq, profile_state) );
2336     Node* tst   = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
2337     // Branch to failure if state was changed
2338     { BuildCutout unless(this, tst, PROB_ALWAYS);
2339       uncommon_trap(Deoptimization::Reason_rtm_state_change,
2340                     Deoptimization::Action_make_not_entrant);
2341     }
2342   }
2343 #endif
2344 }
2345 
2346 //------------------------------return_current---------------------------------
2347 // Append current _map to _exit_return
2348 void Parse::return_current(Node* value) {
2349   if (RegisterFinalizersAtInit &&
2350       method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2351     call_register_finalizer();
2352   }
2353 
2354   // Do not set_parse_bci, so that return goo is credited to the return insn.
2355   // vreturn can trigger an allocation so vreturn can throw. Setting
2356   // the bci here breaks exception handling. Commenting this out
2357   // doesn't seem to break anything.
2358   //  set_bci(InvocationEntryBci);
2359   if (method()->is_synchronized() && GenerateSynchronizationCode) {
2360     shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2361   }
2362   if (C->env()->dtrace_method_probes()) {
2363     make_dtrace_method_exit(method());
2364   }
2365   // frame pointer is always same, already captured
2366   if (value != nullptr) {
2367     Node* phi = _exits.argument(0);
2368     const Type* return_type = phi->bottom_type();
2369     const TypeInstPtr* tr = return_type->isa_instptr();
2370     assert(!value->is_InlineType() || !value->as_InlineType()->is_larval(), "returning a larval");
2371     if ((tf()->returns_inline_type_as_fields() || (_caller->has_method() && !Compile::current()->inlining_incrementally())) &&
2372         return_type->is_inlinetypeptr()) {
2373       // Inline type is returned as fields, make sure it is scalarized
2374       if (!value->is_InlineType()) {
2375         value = InlineTypeNode::make_from_oop(this, value, return_type->inline_klass(), false);
2376       }
2377       if (!_caller->has_method() || Compile::current()->inlining_incrementally()) {
2378         // Returning from root or an incrementally inlined method. Make sure all non-flat
2379         // fields are buffered and re-execute if allocation triggers deoptimization.
2380         PreserveReexecuteState preexecs(this);
2381         assert(tf()->returns_inline_type_as_fields(), "must be returned as fields");
2382         jvms()->set_should_reexecute(true);
2383         inc_sp(1);
2384         value = value->as_InlineType()->allocate_fields(this);
2385       }
2386     } else if (value->is_InlineType()) {
2387       // Inline type is returned as oop, make sure it is buffered and re-execute
2388       // if allocation triggers deoptimization.
2389       PreserveReexecuteState preexecs(this);
2390       jvms()->set_should_reexecute(true);
2391       inc_sp(1);
2392       value = value->as_InlineType()->buffer(this);
2393     }
2394     // ...else
2395     // If returning oops to an interface-return, there is a silent free
2396     // cast from oop to interface allowed by the Verifier. Make it explicit here.
2397     phi->add_req(value);
2398   }
2399 
2400   SafePointNode* exit_return = _exits.map();
2401   exit_return->in( TypeFunc::Control  )->add_req( control() );
2402   exit_return->in( TypeFunc::I_O      )->add_req( i_o    () );
2403   Node *mem = exit_return->in( TypeFunc::Memory   );
2404   for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2405     if (mms.is_empty()) {
2406       // get a copy of the base memory, and patch just this one input
2407       const TypePtr* adr_type = mms.adr_type(C);
2408       Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2409       assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2410       gvn().set_type_bottom(phi);
2411       phi->del_req(phi->req()-1);  // prepare to re-patch
2412       mms.set_memory(phi);
2413     }
2414     mms.memory()->add_req(mms.memory2());
2415   }
2416 
2417   if (_first_return) {
2418     _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2419     _first_return = false;
2420   } else {
2421     _exits.map()->merge_replaced_nodes_with(map());
2422   }
2423 
2424   stop_and_kill_map();          // This CFG path dies here
2425 }
2426 
2427 
2428 //------------------------------add_safepoint----------------------------------
2429 void Parse::add_safepoint() {
2430   uint parms = TypeFunc::Parms+1;
2431 
2432   // Clear out dead values from the debug info.
2433   kill_dead_locals();
2434 
2435   // Clone the JVM State
2436   SafePointNode *sfpnt = new SafePointNode(parms, nullptr);
2437 
2438   // Capture memory state BEFORE a SafePoint.  Since we can block at a
2439   // SafePoint we need our GC state to be safe; i.e. we need all our current
2440   // write barriers (card marks) to not float down after the SafePoint so we
2441   // must read raw memory.  Likewise we need all oop stores to match the card
2442   // marks.  If deopt can happen, we need ALL stores (we need the correct JVM
2443   // state on a deopt).
2444 
2445   // We do not need to WRITE the memory state after a SafePoint.  The control
2446   // edge will keep card-marks and oop-stores from floating up from below a
2447   // SafePoint and our true dependency added here will keep them from floating
2448   // down below a SafePoint.
2449 
2450   // Clone the current memory state
2451   Node* mem = MergeMemNode::make(map()->memory());
2452 
2453   mem = _gvn.transform(mem);
2454 
2455   // Pass control through the safepoint
2456   sfpnt->init_req(TypeFunc::Control  , control());
2457   // Fix edges normally used by a call
2458   sfpnt->init_req(TypeFunc::I_O      , top() );
2459   sfpnt->init_req(TypeFunc::Memory   , mem   );
2460   sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2461   sfpnt->init_req(TypeFunc::FramePtr , top() );
2462 
2463   // Create a node for the polling address
2464   Node *polladr;
2465   Node *thread = _gvn.transform(new ThreadLocalNode());
2466   Node *polling_page_load_addr = _gvn.transform(basic_plus_adr(top(), thread, in_bytes(JavaThread::polling_page_offset())));
2467   polladr = make_load(control(), polling_page_load_addr, TypeRawPtr::BOTTOM, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);
2468   sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2469 
2470   // Fix up the JVM State edges
2471   add_safepoint_edges(sfpnt);
2472   Node *transformed_sfpnt = _gvn.transform(sfpnt);
2473   set_control(transformed_sfpnt);
2474 
2475   // Provide an edge from root to safepoint.  This makes the safepoint
2476   // appear useful until the parse has completed.
2477   if (transformed_sfpnt->is_SafePoint()) {
2478     assert(C->root() != nullptr, "Expect parse is still valid");
2479     C->root()->add_prec(transformed_sfpnt);
2480   }
2481 }
2482 
2483 #ifndef PRODUCT
2484 //------------------------show_parse_info--------------------------------------
2485 void Parse::show_parse_info() {
2486   InlineTree* ilt = nullptr;
2487   if (C->ilt() != nullptr) {
2488     JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2489     ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2490   }
2491   if (PrintCompilation && Verbose) {
2492     if (depth() == 1) {
2493       if( ilt->count_inlines() ) {
2494         tty->print("    __inlined %d (%d bytes)", ilt->count_inlines(),
2495                      ilt->count_inline_bcs());
2496         tty->cr();
2497       }
2498     } else {
2499       if (method()->is_synchronized())         tty->print("s");
2500       if (method()->has_exception_handlers())  tty->print("!");
2501       // Check this is not the final compiled version
2502       if (C->trap_can_recompile()) {
2503         tty->print("-");
2504       } else {
2505         tty->print(" ");
2506       }
2507       method()->print_short_name();
2508       if (is_osr_parse()) {
2509         tty->print(" @ %d", osr_bci());
2510       }
2511       tty->print(" (%d bytes)",method()->code_size());
2512       if (ilt->count_inlines()) {
2513         tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2514                    ilt->count_inline_bcs());
2515       }
2516       tty->cr();
2517     }
2518   }
2519   if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2520     // Print that we succeeded; suppress this message on the first osr parse.
2521 
2522     if (method()->is_synchronized())         tty->print("s");
2523     if (method()->has_exception_handlers())  tty->print("!");
2524     // Check this is not the final compiled version
2525     if (C->trap_can_recompile() && depth() == 1) {
2526       tty->print("-");
2527     } else {
2528       tty->print(" ");
2529     }
2530     if( depth() != 1 ) { tty->print("   "); }  // missing compile count
2531     for (int i = 1; i < depth(); ++i) { tty->print("  "); }
2532     method()->print_short_name();
2533     if (is_osr_parse()) {
2534       tty->print(" @ %d", osr_bci());
2535     }
2536     if (ilt->caller_bci() != -1) {
2537       tty->print(" @ %d", ilt->caller_bci());
2538     }
2539     tty->print(" (%d bytes)",method()->code_size());
2540     if (ilt->count_inlines()) {
2541       tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2542                  ilt->count_inline_bcs());
2543     }
2544     tty->cr();
2545   }
2546 }
2547 
2548 
2549 //------------------------------dump-------------------------------------------
2550 // Dump information associated with the bytecodes of current _method
2551 void Parse::dump() {
2552   if( method() != nullptr ) {
2553     // Iterate over bytecodes
2554     ciBytecodeStream iter(method());
2555     for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2556       dump_bci( iter.cur_bci() );
2557       tty->cr();
2558     }
2559   }
2560 }
2561 
2562 // Dump information associated with a byte code index, 'bci'
2563 void Parse::dump_bci(int bci) {
2564   // Output info on merge-points, cloning, and within _jsr..._ret
2565   // NYI
2566   tty->print(" bci:%d", bci);
2567 }
2568 
2569 #endif