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