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