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