rev 55090 : secret-sfac

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