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