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