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