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