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