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