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