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