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