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