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