graphKit.cpp revision 8413:92457dfb91bd
1/*
2 * Copyright (c) 2001, 2015, 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 "gc/g1/g1SATBCardTableModRefBS.hpp"
28#include "gc/g1/heapRegion.hpp"
29#include "gc/shared/barrierSet.hpp"
30#include "gc/shared/cardTableModRefBS.hpp"
31#include "gc/shared/collectedHeap.hpp"
32#include "opto/addnode.hpp"
33#include "opto/castnode.hpp"
34#include "opto/convertnode.hpp"
35#include "opto/graphKit.hpp"
36#include "opto/idealKit.hpp"
37#include "opto/intrinsicnode.hpp"
38#include "opto/locknode.hpp"
39#include "opto/machnode.hpp"
40#include "opto/opaquenode.hpp"
41#include "opto/parse.hpp"
42#include "opto/rootnode.hpp"
43#include "opto/runtime.hpp"
44#include "runtime/deoptimization.hpp"
45#include "runtime/sharedRuntime.hpp"
46
47//----------------------------GraphKit-----------------------------------------
48// Main utility constructor.
49GraphKit::GraphKit(JVMState* jvms)
50  : Phase(Phase::Parser),
51    _env(C->env()),
52    _gvn(*C->initial_gvn())
53{
54  _exceptions = jvms->map()->next_exception();
55  if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
56  set_jvms(jvms);
57}
58
59// Private constructor for parser.
60GraphKit::GraphKit()
61  : Phase(Phase::Parser),
62    _env(C->env()),
63    _gvn(*C->initial_gvn())
64{
65  _exceptions = NULL;
66  set_map(NULL);
67  debug_only(_sp = -99);
68  debug_only(set_bci(-99));
69}
70
71
72
73//---------------------------clean_stack---------------------------------------
74// Clear away rubbish from the stack area of the JVM state.
75// This destroys any arguments that may be waiting on the stack.
76void GraphKit::clean_stack(int from_sp) {
77  SafePointNode* map      = this->map();
78  JVMState*      jvms     = this->jvms();
79  int            stk_size = jvms->stk_size();
80  int            stkoff   = jvms->stkoff();
81  Node*          top      = this->top();
82  for (int i = from_sp; i < stk_size; i++) {
83    if (map->in(stkoff + i) != top) {
84      map->set_req(stkoff + i, top);
85    }
86  }
87}
88
89
90//--------------------------------sync_jvms-----------------------------------
91// Make sure our current jvms agrees with our parse state.
92JVMState* GraphKit::sync_jvms() const {
93  JVMState* jvms = this->jvms();
94  jvms->set_bci(bci());       // Record the new bci in the JVMState
95  jvms->set_sp(sp());         // Record the new sp in the JVMState
96  assert(jvms_in_sync(), "jvms is now in sync");
97  return jvms;
98}
99
100//--------------------------------sync_jvms_for_reexecute---------------------
101// Make sure our current jvms agrees with our parse state.  This version
102// uses the reexecute_sp for reexecuting bytecodes.
103JVMState* GraphKit::sync_jvms_for_reexecute() {
104  JVMState* jvms = this->jvms();
105  jvms->set_bci(bci());          // Record the new bci in the JVMState
106  jvms->set_sp(reexecute_sp());  // Record the new sp in the JVMState
107  return jvms;
108}
109
110#ifdef ASSERT
111bool GraphKit::jvms_in_sync() const {
112  Parse* parse = is_Parse();
113  if (parse == NULL) {
114    if (bci() !=      jvms()->bci())          return false;
115    if (sp()  != (int)jvms()->sp())           return false;
116    return true;
117  }
118  if (jvms()->method() != parse->method())    return false;
119  if (jvms()->bci()    != parse->bci())       return false;
120  int jvms_sp = jvms()->sp();
121  if (jvms_sp          != parse->sp())        return false;
122  int jvms_depth = jvms()->depth();
123  if (jvms_depth       != parse->depth())     return false;
124  return true;
125}
126
127// Local helper checks for special internal merge points
128// used to accumulate and merge exception states.
129// They are marked by the region's in(0) edge being the map itself.
130// Such merge points must never "escape" into the parser at large,
131// until they have been handed to gvn.transform.
132static bool is_hidden_merge(Node* reg) {
133  if (reg == NULL)  return false;
134  if (reg->is_Phi()) {
135    reg = reg->in(0);
136    if (reg == NULL)  return false;
137  }
138  return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();
139}
140
141void GraphKit::verify_map() const {
142  if (map() == NULL)  return;  // null map is OK
143  assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");
144  assert(!map()->has_exceptions(),    "call add_exception_states_from 1st");
145  assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");
146}
147
148void GraphKit::verify_exception_state(SafePointNode* ex_map) {
149  assert(ex_map->next_exception() == NULL, "not already part of a chain");
150  assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");
151}
152#endif
153
154//---------------------------stop_and_kill_map---------------------------------
155// Set _map to NULL, signalling a stop to further bytecode execution.
156// First smash the current map's control to a constant, to mark it dead.
157void GraphKit::stop_and_kill_map() {
158  SafePointNode* dead_map = stop();
159  if (dead_map != NULL) {
160    dead_map->disconnect_inputs(NULL, C); // Mark the map as killed.
161    assert(dead_map->is_killed(), "must be so marked");
162  }
163}
164
165
166//--------------------------------stopped--------------------------------------
167// Tell if _map is NULL, or control is top.
168bool GraphKit::stopped() {
169  if (map() == NULL)           return true;
170  else if (control() == top()) return true;
171  else                         return false;
172}
173
174
175//-----------------------------has_ex_handler----------------------------------
176// Tell if this method or any caller method has exception handlers.
177bool GraphKit::has_ex_handler() {
178  for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {
179    if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {
180      return true;
181    }
182  }
183  return false;
184}
185
186//------------------------------save_ex_oop------------------------------------
187// Save an exception without blowing stack contents or other JVM state.
188void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {
189  assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");
190  ex_map->add_req(ex_oop);
191  debug_only(verify_exception_state(ex_map));
192}
193
194inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {
195  assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");
196  Node* ex_oop = ex_map->in(ex_map->req()-1);
197  if (clear_it)  ex_map->del_req(ex_map->req()-1);
198  return ex_oop;
199}
200
201//-----------------------------saved_ex_oop------------------------------------
202// Recover a saved exception from its map.
203Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {
204  return common_saved_ex_oop(ex_map, false);
205}
206
207//--------------------------clear_saved_ex_oop---------------------------------
208// Erase a previously saved exception from its map.
209Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {
210  return common_saved_ex_oop(ex_map, true);
211}
212
213#ifdef ASSERT
214//---------------------------has_saved_ex_oop----------------------------------
215// Erase a previously saved exception from its map.
216bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {
217  return ex_map->req() == ex_map->jvms()->endoff()+1;
218}
219#endif
220
221//-------------------------make_exception_state--------------------------------
222// Turn the current JVM state into an exception state, appending the ex_oop.
223SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {
224  sync_jvms();
225  SafePointNode* ex_map = stop();  // do not manipulate this map any more
226  set_saved_ex_oop(ex_map, ex_oop);
227  return ex_map;
228}
229
230
231//--------------------------add_exception_state--------------------------------
232// Add an exception to my list of exceptions.
233void GraphKit::add_exception_state(SafePointNode* ex_map) {
234  if (ex_map == NULL || ex_map->control() == top()) {
235    return;
236  }
237#ifdef ASSERT
238  verify_exception_state(ex_map);
239  if (has_exceptions()) {
240    assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");
241  }
242#endif
243
244  // If there is already an exception of exactly this type, merge with it.
245  // In particular, null-checks and other low-level exceptions common up here.
246  Node*       ex_oop  = saved_ex_oop(ex_map);
247  const Type* ex_type = _gvn.type(ex_oop);
248  if (ex_oop == top()) {
249    // No action needed.
250    return;
251  }
252  assert(ex_type->isa_instptr(), "exception must be an instance");
253  for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {
254    const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));
255    // We check sp also because call bytecodes can generate exceptions
256    // both before and after arguments are popped!
257    if (ex_type2 == ex_type
258        && e2->_jvms->sp() == ex_map->_jvms->sp()) {
259      combine_exception_states(ex_map, e2);
260      return;
261    }
262  }
263
264  // No pre-existing exception of the same type.  Chain it on the list.
265  push_exception_state(ex_map);
266}
267
268//-----------------------add_exception_states_from-----------------------------
269void GraphKit::add_exception_states_from(JVMState* jvms) {
270  SafePointNode* ex_map = jvms->map()->next_exception();
271  if (ex_map != NULL) {
272    jvms->map()->set_next_exception(NULL);
273    for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {
274      next_map = ex_map->next_exception();
275      ex_map->set_next_exception(NULL);
276      add_exception_state(ex_map);
277    }
278  }
279}
280
281//-----------------------transfer_exceptions_into_jvms-------------------------
282JVMState* GraphKit::transfer_exceptions_into_jvms() {
283  if (map() == NULL) {
284    // We need a JVMS to carry the exceptions, but the map has gone away.
285    // Create a scratch JVMS, cloned from any of the exception states...
286    if (has_exceptions()) {
287      _map = _exceptions;
288      _map = clone_map();
289      _map->set_next_exception(NULL);
290      clear_saved_ex_oop(_map);
291      debug_only(verify_map());
292    } else {
293      // ...or created from scratch
294      JVMState* jvms = new (C) JVMState(_method, NULL);
295      jvms->set_bci(_bci);
296      jvms->set_sp(_sp);
297      jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));
298      set_jvms(jvms);
299      for (uint i = 0; i < map()->req(); i++)  map()->init_req(i, top());
300      set_all_memory(top());
301      while (map()->req() < jvms->endoff())  map()->add_req(top());
302    }
303    // (This is a kludge, in case you didn't notice.)
304    set_control(top());
305  }
306  JVMState* jvms = sync_jvms();
307  assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");
308  jvms->map()->set_next_exception(_exceptions);
309  _exceptions = NULL;   // done with this set of exceptions
310  return jvms;
311}
312
313static inline void add_n_reqs(Node* dstphi, Node* srcphi) {
314  assert(is_hidden_merge(dstphi), "must be a special merge node");
315  assert(is_hidden_merge(srcphi), "must be a special merge node");
316  uint limit = srcphi->req();
317  for (uint i = PhiNode::Input; i < limit; i++) {
318    dstphi->add_req(srcphi->in(i));
319  }
320}
321static inline void add_one_req(Node* dstphi, Node* src) {
322  assert(is_hidden_merge(dstphi), "must be a special merge node");
323  assert(!is_hidden_merge(src), "must not be a special merge node");
324  dstphi->add_req(src);
325}
326
327//-----------------------combine_exception_states------------------------------
328// This helper function combines exception states by building phis on a
329// specially marked state-merging region.  These regions and phis are
330// untransformed, and can build up gradually.  The region is marked by
331// having a control input of its exception map, rather than NULL.  Such
332// regions do not appear except in this function, and in use_exception_state.
333void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
334  if (failing())  return;  // dying anyway...
335  JVMState* ex_jvms = ex_map->_jvms;
336  assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
337  assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
338  assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
339  assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
340  assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
341  assert(ex_map->req() == phi_map->req(), "matching maps");
342  uint tos = ex_jvms->stkoff() + ex_jvms->sp();
343  Node*         hidden_merge_mark = root();
344  Node*         region  = phi_map->control();
345  MergeMemNode* phi_mem = phi_map->merged_memory();
346  MergeMemNode* ex_mem  = ex_map->merged_memory();
347  if (region->in(0) != hidden_merge_mark) {
348    // The control input is not (yet) a specially-marked region in phi_map.
349    // Make it so, and build some phis.
350    region = new RegionNode(2);
351    _gvn.set_type(region, Type::CONTROL);
352    region->set_req(0, hidden_merge_mark);  // marks an internal ex-state
353    region->init_req(1, phi_map->control());
354    phi_map->set_control(region);
355    Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
356    record_for_igvn(io_phi);
357    _gvn.set_type(io_phi, Type::ABIO);
358    phi_map->set_i_o(io_phi);
359    for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {
360      Node* m = mms.memory();
361      Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));
362      record_for_igvn(m_phi);
363      _gvn.set_type(m_phi, Type::MEMORY);
364      mms.set_memory(m_phi);
365    }
366  }
367
368  // Either or both of phi_map and ex_map might already be converted into phis.
369  Node* ex_control = ex_map->control();
370  // if there is special marking on ex_map also, we add multiple edges from src
371  bool add_multiple = (ex_control->in(0) == hidden_merge_mark);
372  // how wide was the destination phi_map, originally?
373  uint orig_width = region->req();
374
375  if (add_multiple) {
376    add_n_reqs(region, ex_control);
377    add_n_reqs(phi_map->i_o(), ex_map->i_o());
378  } else {
379    // ex_map has no merges, so we just add single edges everywhere
380    add_one_req(region, ex_control);
381    add_one_req(phi_map->i_o(), ex_map->i_o());
382  }
383  for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {
384    if (mms.is_empty()) {
385      // get a copy of the base memory, and patch some inputs into it
386      const TypePtr* adr_type = mms.adr_type(C);
387      Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
388      assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
389      mms.set_memory(phi);
390      // Prepare to append interesting stuff onto the newly sliced phi:
391      while (phi->req() > orig_width)  phi->del_req(phi->req()-1);
392    }
393    // Append stuff from ex_map:
394    if (add_multiple) {
395      add_n_reqs(mms.memory(), mms.memory2());
396    } else {
397      add_one_req(mms.memory(), mms.memory2());
398    }
399  }
400  uint limit = ex_map->req();
401  for (uint i = TypeFunc::Parms; i < limit; i++) {
402    // Skip everything in the JVMS after tos.  (The ex_oop follows.)
403    if (i == tos)  i = ex_jvms->monoff();
404    Node* src = ex_map->in(i);
405    Node* dst = phi_map->in(i);
406    if (src != dst) {
407      PhiNode* phi;
408      if (dst->in(0) != region) {
409        dst = phi = PhiNode::make(region, dst, _gvn.type(dst));
410        record_for_igvn(phi);
411        _gvn.set_type(phi, phi->type());
412        phi_map->set_req(i, dst);
413        // Prepare to append interesting stuff onto the new phi:
414        while (dst->req() > orig_width)  dst->del_req(dst->req()-1);
415      } else {
416        assert(dst->is_Phi(), "nobody else uses a hidden region");
417        phi = dst->as_Phi();
418      }
419      if (add_multiple && src->in(0) == ex_control) {
420        // Both are phis.
421        add_n_reqs(dst, src);
422      } else {
423        while (dst->req() < region->req())  add_one_req(dst, src);
424      }
425      const Type* srctype = _gvn.type(src);
426      if (phi->type() != srctype) {
427        const Type* dsttype = phi->type()->meet_speculative(srctype);
428        if (phi->type() != dsttype) {
429          phi->set_type(dsttype);
430          _gvn.set_type(phi, dsttype);
431        }
432      }
433    }
434  }
435  phi_map->merge_replaced_nodes_with(ex_map);
436}
437
438//--------------------------use_exception_state--------------------------------
439Node* GraphKit::use_exception_state(SafePointNode* phi_map) {
440  if (failing()) { stop(); return top(); }
441  Node* region = phi_map->control();
442  Node* hidden_merge_mark = root();
443  assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");
444  Node* ex_oop = clear_saved_ex_oop(phi_map);
445  if (region->in(0) == hidden_merge_mark) {
446    // Special marking for internal ex-states.  Process the phis now.
447    region->set_req(0, region);  // now it's an ordinary region
448    set_jvms(phi_map->jvms());   // ...so now we can use it as a map
449    // Note: Setting the jvms also sets the bci and sp.
450    set_control(_gvn.transform(region));
451    uint tos = jvms()->stkoff() + sp();
452    for (uint i = 1; i < tos; i++) {
453      Node* x = phi_map->in(i);
454      if (x->in(0) == region) {
455        assert(x->is_Phi(), "expected a special phi");
456        phi_map->set_req(i, _gvn.transform(x));
457      }
458    }
459    for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
460      Node* x = mms.memory();
461      if (x->in(0) == region) {
462        assert(x->is_Phi(), "nobody else uses a hidden region");
463        mms.set_memory(_gvn.transform(x));
464      }
465    }
466    if (ex_oop->in(0) == region) {
467      assert(ex_oop->is_Phi(), "expected a special phi");
468      ex_oop = _gvn.transform(ex_oop);
469    }
470  } else {
471    set_jvms(phi_map->jvms());
472  }
473
474  assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");
475  assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");
476  return ex_oop;
477}
478
479//---------------------------------java_bc-------------------------------------
480Bytecodes::Code GraphKit::java_bc() const {
481  ciMethod* method = this->method();
482  int       bci    = this->bci();
483  if (method != NULL && bci != InvocationEntryBci)
484    return method->java_code_at_bci(bci);
485  else
486    return Bytecodes::_illegal;
487}
488
489void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
490                                                          bool must_throw) {
491    // if the exception capability is set, then we will generate code
492    // to check the JavaThread.should_post_on_exceptions flag to see
493    // if we actually need to report exception events (for this
494    // thread).  If we don't need to report exception events, we will
495    // take the normal fast path provided by add_exception_events.  If
496    // exception event reporting is enabled for this thread, we will
497    // take the uncommon_trap in the BuildCutout below.
498
499    // first must access the should_post_on_exceptions_flag in this thread's JavaThread
500    Node* jthread = _gvn.transform(new ThreadLocalNode());
501    Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));
502    Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);
503
504    // Test the should_post_on_exceptions_flag vs. 0
505    Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );
506    Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
507
508    // Branch to slow_path if should_post_on_exceptions_flag was true
509    { BuildCutout unless(this, tst, PROB_MAX);
510      // Do not try anything fancy if we're notifying the VM on every throw.
511      // Cf. case Bytecodes::_athrow in parse2.cpp.
512      uncommon_trap(reason, Deoptimization::Action_none,
513                    (ciKlass*)NULL, (char*)NULL, must_throw);
514    }
515
516}
517
518//------------------------------builtin_throw----------------------------------
519void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {
520  bool must_throw = true;
521
522  if (env()->jvmti_can_post_on_exceptions()) {
523    // check if we must post exception events, take uncommon trap if so
524    uncommon_trap_if_should_post_on_exceptions(reason, must_throw);
525    // here if should_post_on_exceptions is false
526    // continue on with the normal codegen
527  }
528
529  // If this particular condition has not yet happened at this
530  // bytecode, then use the uncommon trap mechanism, and allow for
531  // a future recompilation if several traps occur here.
532  // If the throw is hot, try to use a more complicated inline mechanism
533  // which keeps execution inside the compiled code.
534  bool treat_throw_as_hot = false;
535  ciMethodData* md = method()->method_data();
536
537  if (ProfileTraps) {
538    if (too_many_traps(reason)) {
539      treat_throw_as_hot = true;
540    }
541    // (If there is no MDO at all, assume it is early in
542    // execution, and that any deopts are part of the
543    // startup transient, and don't need to be remembered.)
544
545    // Also, if there is a local exception handler, treat all throws
546    // as hot if there has been at least one in this method.
547    if (C->trap_count(reason) != 0
548        && method()->method_data()->trap_count(reason) != 0
549        && has_ex_handler()) {
550        treat_throw_as_hot = true;
551    }
552  }
553
554  // If this throw happens frequently, an uncommon trap might cause
555  // a performance pothole.  If there is a local exception handler,
556  // and if this particular bytecode appears to be deoptimizing often,
557  // let us handle the throw inline, with a preconstructed instance.
558  // Note:   If the deopt count has blown up, the uncommon trap
559  // runtime is going to flush this nmethod, not matter what.
560  if (treat_throw_as_hot
561      && (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {
562    // If the throw is local, we use a pre-existing instance and
563    // punt on the backtrace.  This would lead to a missing backtrace
564    // (a repeat of 4292742) if the backtrace object is ever asked
565    // for its backtrace.
566    // Fixing this remaining case of 4292742 requires some flavor of
567    // escape analysis.  Leave that for the future.
568    ciInstance* ex_obj = NULL;
569    switch (reason) {
570    case Deoptimization::Reason_null_check:
571      ex_obj = env()->NullPointerException_instance();
572      break;
573    case Deoptimization::Reason_div0_check:
574      ex_obj = env()->ArithmeticException_instance();
575      break;
576    case Deoptimization::Reason_range_check:
577      ex_obj = env()->ArrayIndexOutOfBoundsException_instance();
578      break;
579    case Deoptimization::Reason_class_check:
580      if (java_bc() == Bytecodes::_aastore) {
581        ex_obj = env()->ArrayStoreException_instance();
582      } else {
583        ex_obj = env()->ClassCastException_instance();
584      }
585      break;
586    }
587    if (failing()) { stop(); return; }  // exception allocation might fail
588    if (ex_obj != NULL) {
589      // Cheat with a preallocated exception object.
590      if (C->log() != NULL)
591        C->log()->elem("hot_throw preallocated='1' reason='%s'",
592                       Deoptimization::trap_reason_name(reason));
593      const TypeInstPtr* ex_con  = TypeInstPtr::make(ex_obj);
594      Node*              ex_node = _gvn.transform(ConNode::make(ex_con));
595
596      // Clear the detail message of the preallocated exception object.
597      // Weblogic sometimes mutates the detail message of exceptions
598      // using reflection.
599      int offset = java_lang_Throwable::get_detailMessage_offset();
600      const TypePtr* adr_typ = ex_con->add_offset(offset);
601
602      Node *adr = basic_plus_adr(ex_node, ex_node, offset);
603      const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());
604      // Conservatively release stores of object references.
605      Node *store = store_oop_to_object(control(), ex_node, adr, adr_typ, null(), val_type, T_OBJECT, MemNode::release);
606
607      add_exception_state(make_exception_state(ex_node));
608      return;
609    }
610  }
611
612  // %%% Maybe add entry to OptoRuntime which directly throws the exc.?
613  // It won't be much cheaper than bailing to the interp., since we'll
614  // have to pass up all the debug-info, and the runtime will have to
615  // create the stack trace.
616
617  // Usual case:  Bail to interpreter.
618  // Reserve the right to recompile if we haven't seen anything yet.
619
620  ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : NULL;
621  Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;
622  if (treat_throw_as_hot
623      && (method()->method_data()->trap_recompiled_at(bci(), m)
624          || C->too_many_traps(reason))) {
625    // We cannot afford to take more traps here.  Suffer in the interpreter.
626    if (C->log() != NULL)
627      C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",
628                     Deoptimization::trap_reason_name(reason),
629                     C->trap_count(reason));
630    action = Deoptimization::Action_none;
631  }
632
633  // "must_throw" prunes the JVM state to include only the stack, if there
634  // are no local exception handlers.  This should cut down on register
635  // allocation time and code size, by drastically reducing the number
636  // of in-edges on the call to the uncommon trap.
637
638  uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);
639}
640
641
642//----------------------------PreserveJVMState---------------------------------
643PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {
644  debug_only(kit->verify_map());
645  _kit    = kit;
646  _map    = kit->map();   // preserve the map
647  _sp     = kit->sp();
648  kit->set_map(clone_map ? kit->clone_map() : NULL);
649#ifdef ASSERT
650  _bci    = kit->bci();
651  Parse* parser = kit->is_Parse();
652  int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
653  _block  = block;
654#endif
655}
656PreserveJVMState::~PreserveJVMState() {
657  GraphKit* kit = _kit;
658#ifdef ASSERT
659  assert(kit->bci() == _bci, "bci must not shift");
660  Parse* parser = kit->is_Parse();
661  int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
662  assert(block == _block,    "block must not shift");
663#endif
664  kit->set_map(_map);
665  kit->set_sp(_sp);
666}
667
668
669//-----------------------------BuildCutout-------------------------------------
670BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)
671  : PreserveJVMState(kit)
672{
673  assert(p->is_Con() || p->is_Bool(), "test must be a bool");
674  SafePointNode* outer_map = _map;   // preserved map is caller's
675  SafePointNode* inner_map = kit->map();
676  IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);
677  outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));
678  inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));
679}
680BuildCutout::~BuildCutout() {
681  GraphKit* kit = _kit;
682  assert(kit->stopped(), "cutout code must stop, throw, return, etc.");
683}
684
685//---------------------------PreserveReexecuteState----------------------------
686PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {
687  assert(!kit->stopped(), "must call stopped() before");
688  _kit    =    kit;
689  _sp     =    kit->sp();
690  _reexecute = kit->jvms()->_reexecute;
691}
692PreserveReexecuteState::~PreserveReexecuteState() {
693  if (_kit->stopped()) return;
694  _kit->jvms()->_reexecute = _reexecute;
695  _kit->set_sp(_sp);
696}
697
698//------------------------------clone_map--------------------------------------
699// Implementation of PreserveJVMState
700//
701// Only clone_map(...) here. If this function is only used in the
702// PreserveJVMState class we may want to get rid of this extra
703// function eventually and do it all there.
704
705SafePointNode* GraphKit::clone_map() {
706  if (map() == NULL)  return NULL;
707
708  // Clone the memory edge first
709  Node* mem = MergeMemNode::make(map()->memory());
710  gvn().set_type_bottom(mem);
711
712  SafePointNode *clonemap = (SafePointNode*)map()->clone();
713  JVMState* jvms = this->jvms();
714  JVMState* clonejvms = jvms->clone_shallow(C);
715  clonemap->set_memory(mem);
716  clonemap->set_jvms(clonejvms);
717  clonejvms->set_map(clonemap);
718  record_for_igvn(clonemap);
719  gvn().set_type_bottom(clonemap);
720  return clonemap;
721}
722
723
724//-----------------------------set_map_clone-----------------------------------
725void GraphKit::set_map_clone(SafePointNode* m) {
726  _map = m;
727  _map = clone_map();
728  _map->set_next_exception(NULL);
729  debug_only(verify_map());
730}
731
732
733//----------------------------kill_dead_locals---------------------------------
734// Detect any locals which are known to be dead, and force them to top.
735void GraphKit::kill_dead_locals() {
736  // Consult the liveness information for the locals.  If any
737  // of them are unused, then they can be replaced by top().  This
738  // should help register allocation time and cut down on the size
739  // of the deoptimization information.
740
741  // This call is made from many of the bytecode handling
742  // subroutines called from the Big Switch in do_one_bytecode.
743  // Every bytecode which might include a slow path is responsible
744  // for killing its dead locals.  The more consistent we
745  // are about killing deads, the fewer useless phis will be
746  // constructed for them at various merge points.
747
748  // bci can be -1 (InvocationEntryBci).  We return the entry
749  // liveness for the method.
750
751  if (method() == NULL || method()->code_size() == 0) {
752    // We are building a graph for a call to a native method.
753    // All locals are live.
754    return;
755  }
756
757  ResourceMark rm;
758
759  // Consult the liveness information for the locals.  If any
760  // of them are unused, then they can be replaced by top().  This
761  // should help register allocation time and cut down on the size
762  // of the deoptimization information.
763  MethodLivenessResult live_locals = method()->liveness_at_bci(bci());
764
765  int len = (int)live_locals.size();
766  assert(len <= jvms()->loc_size(), "too many live locals");
767  for (int local = 0; local < len; local++) {
768    if (!live_locals.at(local)) {
769      set_local(local, top());
770    }
771  }
772}
773
774#ifdef ASSERT
775//-------------------------dead_locals_are_killed------------------------------
776// Return true if all dead locals are set to top in the map.
777// Used to assert "clean" debug info at various points.
778bool GraphKit::dead_locals_are_killed() {
779  if (method() == NULL || method()->code_size() == 0) {
780    // No locals need to be dead, so all is as it should be.
781    return true;
782  }
783
784  // Make sure somebody called kill_dead_locals upstream.
785  ResourceMark rm;
786  for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
787    if (jvms->loc_size() == 0)  continue;  // no locals to consult
788    SafePointNode* map = jvms->map();
789    ciMethod* method = jvms->method();
790    int       bci    = jvms->bci();
791    if (jvms == this->jvms()) {
792      bci = this->bci();  // it might not yet be synched
793    }
794    MethodLivenessResult live_locals = method->liveness_at_bci(bci);
795    int len = (int)live_locals.size();
796    if (!live_locals.is_valid() || len == 0)
797      // This method is trivial, or is poisoned by a breakpoint.
798      return true;
799    assert(len == jvms->loc_size(), "live map consistent with locals map");
800    for (int local = 0; local < len; local++) {
801      if (!live_locals.at(local) && map->local(jvms, local) != top()) {
802        if (PrintMiscellaneous && (Verbose || WizardMode)) {
803          tty->print_cr("Zombie local %d: ", local);
804          jvms->dump();
805        }
806        return false;
807      }
808    }
809  }
810  return true;
811}
812
813#endif //ASSERT
814
815// Helper function for enforcing certain bytecodes to reexecute if
816// deoptimization happens
817static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
818  ciMethod* cur_method = jvms->method();
819  int       cur_bci   = jvms->bci();
820  if (cur_method != NULL && cur_bci != InvocationEntryBci) {
821    Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
822    return Interpreter::bytecode_should_reexecute(code) ||
823           is_anewarray && code == Bytecodes::_multianewarray;
824    // Reexecute _multianewarray bytecode which was replaced with
825    // sequence of [a]newarray. See Parse::do_multianewarray().
826    //
827    // Note: interpreter should not have it set since this optimization
828    // is limited by dimensions and guarded by flag so in some cases
829    // multianewarray() runtime calls will be generated and
830    // the bytecode should not be reexecutes (stack will not be reset).
831  } else
832    return false;
833}
834
835// Helper function for adding JVMState and debug information to node
836void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
837  // Add the safepoint edges to the call (or other safepoint).
838
839  // Make sure dead locals are set to top.  This
840  // should help register allocation time and cut down on the size
841  // of the deoptimization information.
842  assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
843
844  // Walk the inline list to fill in the correct set of JVMState's
845  // Also fill in the associated edges for each JVMState.
846
847  // If the bytecode needs to be reexecuted we need to put
848  // the arguments back on the stack.
849  const bool should_reexecute = jvms()->should_reexecute();
850  JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
851
852  // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to
853  // undefined if the bci is different.  This is normal for Parse but it
854  // should not happen for LibraryCallKit because only one bci is processed.
855  assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),
856         "in LibraryCallKit the reexecute bit should not change");
857
858  // If we are guaranteed to throw, we can prune everything but the
859  // input to the current bytecode.
860  bool can_prune_locals = false;
861  uint stack_slots_not_pruned = 0;
862  int inputs = 0, depth = 0;
863  if (must_throw) {
864    assert(method() == youngest_jvms->method(), "sanity");
865    if (compute_stack_effects(inputs, depth)) {
866      can_prune_locals = true;
867      stack_slots_not_pruned = inputs;
868    }
869  }
870
871  if (env()->should_retain_local_variables()) {
872    // At any safepoint, this method can get breakpointed, which would
873    // then require an immediate deoptimization.
874    can_prune_locals = false;  // do not prune locals
875    stack_slots_not_pruned = 0;
876  }
877
878  // do not scribble on the input jvms
879  JVMState* out_jvms = youngest_jvms->clone_deep(C);
880  call->set_jvms(out_jvms); // Start jvms list for call node
881
882  // For a known set of bytecodes, the interpreter should reexecute them if
883  // deoptimization happens. We set the reexecute state for them here
884  if (out_jvms->is_reexecute_undefined() && //don't change if already specified
885      should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
886    out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
887  }
888
889  // Presize the call:
890  DEBUG_ONLY(uint non_debug_edges = call->req());
891  call->add_req_batch(top(), youngest_jvms->debug_depth());
892  assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
893
894  // Set up edges so that the call looks like this:
895  //  Call [state:] ctl io mem fptr retadr
896  //       [parms:] parm0 ... parmN
897  //       [root:]  loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
898  //    [...mid:]   loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
899  //       [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
900  // Note that caller debug info precedes callee debug info.
901
902  // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
903  uint debug_ptr = call->req();
904
905  // Loop over the map input edges associated with jvms, add them
906  // to the call node, & reset all offsets to match call node array.
907  for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {
908    uint debug_end   = debug_ptr;
909    uint debug_start = debug_ptr - in_jvms->debug_size();
910    debug_ptr = debug_start;  // back up the ptr
911
912    uint p = debug_start;  // walks forward in [debug_start, debug_end)
913    uint j, k, l;
914    SafePointNode* in_map = in_jvms->map();
915    out_jvms->set_map(call);
916
917    if (can_prune_locals) {
918      assert(in_jvms->method() == out_jvms->method(), "sanity");
919      // If the current throw can reach an exception handler in this JVMS,
920      // then we must keep everything live that can reach that handler.
921      // As a quick and dirty approximation, we look for any handlers at all.
922      if (in_jvms->method()->has_exception_handlers()) {
923        can_prune_locals = false;
924      }
925    }
926
927    // Add the Locals
928    k = in_jvms->locoff();
929    l = in_jvms->loc_size();
930    out_jvms->set_locoff(p);
931    if (!can_prune_locals) {
932      for (j = 0; j < l; j++)
933        call->set_req(p++, in_map->in(k+j));
934    } else {
935      p += l;  // already set to top above by add_req_batch
936    }
937
938    // Add the Expression Stack
939    k = in_jvms->stkoff();
940    l = in_jvms->sp();
941    out_jvms->set_stkoff(p);
942    if (!can_prune_locals) {
943      for (j = 0; j < l; j++)
944        call->set_req(p++, in_map->in(k+j));
945    } else if (can_prune_locals && stack_slots_not_pruned != 0) {
946      // Divide stack into {S0,...,S1}, where S0 is set to top.
947      uint s1 = stack_slots_not_pruned;
948      stack_slots_not_pruned = 0;  // for next iteration
949      if (s1 > l)  s1 = l;
950      uint s0 = l - s1;
951      p += s0;  // skip the tops preinstalled by add_req_batch
952      for (j = s0; j < l; j++)
953        call->set_req(p++, in_map->in(k+j));
954    } else {
955      p += l;  // already set to top above by add_req_batch
956    }
957
958    // Add the Monitors
959    k = in_jvms->monoff();
960    l = in_jvms->mon_size();
961    out_jvms->set_monoff(p);
962    for (j = 0; j < l; j++)
963      call->set_req(p++, in_map->in(k+j));
964
965    // Copy any scalar object fields.
966    k = in_jvms->scloff();
967    l = in_jvms->scl_size();
968    out_jvms->set_scloff(p);
969    for (j = 0; j < l; j++)
970      call->set_req(p++, in_map->in(k+j));
971
972    // Finish the new jvms.
973    out_jvms->set_endoff(p);
974
975    assert(out_jvms->endoff()     == debug_end,             "fill ptr must match");
976    assert(out_jvms->depth()      == in_jvms->depth(),      "depth must match");
977    assert(out_jvms->loc_size()   == in_jvms->loc_size(),   "size must match");
978    assert(out_jvms->mon_size()   == in_jvms->mon_size(),   "size must match");
979    assert(out_jvms->scl_size()   == in_jvms->scl_size(),   "size must match");
980    assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
981
982    // Update the two tail pointers in parallel.
983    out_jvms = out_jvms->caller();
984    in_jvms  = in_jvms->caller();
985  }
986
987  assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
988
989  // Test the correctness of JVMState::debug_xxx accessors:
990  assert(call->jvms()->debug_start() == non_debug_edges, "");
991  assert(call->jvms()->debug_end()   == call->req(), "");
992  assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
993}
994
995bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
996  Bytecodes::Code code = java_bc();
997  if (code == Bytecodes::_wide) {
998    code = method()->java_code_at_bci(bci() + 1);
999  }
1000
1001  BasicType rtype = T_ILLEGAL;
1002  int       rsize = 0;
1003
1004  if (code != Bytecodes::_illegal) {
1005    depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1006    rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1007    if (rtype < T_CONFLICT)
1008      rsize = type2size[rtype];
1009  }
1010
1011  switch (code) {
1012  case Bytecodes::_illegal:
1013    return false;
1014
1015  case Bytecodes::_ldc:
1016  case Bytecodes::_ldc_w:
1017  case Bytecodes::_ldc2_w:
1018    inputs = 0;
1019    break;
1020
1021  case Bytecodes::_dup:         inputs = 1;  break;
1022  case Bytecodes::_dup_x1:      inputs = 2;  break;
1023  case Bytecodes::_dup_x2:      inputs = 3;  break;
1024  case Bytecodes::_dup2:        inputs = 2;  break;
1025  case Bytecodes::_dup2_x1:     inputs = 3;  break;
1026  case Bytecodes::_dup2_x2:     inputs = 4;  break;
1027  case Bytecodes::_swap:        inputs = 2;  break;
1028  case Bytecodes::_arraylength: inputs = 1;  break;
1029
1030  case Bytecodes::_getstatic:
1031  case Bytecodes::_putstatic:
1032  case Bytecodes::_getfield:
1033  case Bytecodes::_putfield:
1034    {
1035      bool ignored_will_link;
1036      ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1037      int      size  = field->type()->size();
1038      bool is_get = (depth >= 0), is_static = (depth & 1);
1039      inputs = (is_static ? 0 : 1);
1040      if (is_get) {
1041        depth = size - inputs;
1042      } else {
1043        inputs += size;        // putxxx pops the value from the stack
1044        depth = - inputs;
1045      }
1046    }
1047    break;
1048
1049  case Bytecodes::_invokevirtual:
1050  case Bytecodes::_invokespecial:
1051  case Bytecodes::_invokestatic:
1052  case Bytecodes::_invokedynamic:
1053  case Bytecodes::_invokeinterface:
1054    {
1055      bool ignored_will_link;
1056      ciSignature* declared_signature = NULL;
1057      ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1058      assert(declared_signature != NULL, "cannot be null");
1059      inputs   = declared_signature->arg_size_for_bc(code);
1060      int size = declared_signature->return_type()->size();
1061      depth = size - inputs;
1062    }
1063    break;
1064
1065  case Bytecodes::_multianewarray:
1066    {
1067      ciBytecodeStream iter(method());
1068      iter.reset_to_bci(bci());
1069      iter.next();
1070      inputs = iter.get_dimensions();
1071      assert(rsize == 1, "");
1072      depth = rsize - inputs;
1073    }
1074    break;
1075
1076  case Bytecodes::_ireturn:
1077  case Bytecodes::_lreturn:
1078  case Bytecodes::_freturn:
1079  case Bytecodes::_dreturn:
1080  case Bytecodes::_areturn:
1081    assert(rsize = -depth, "");
1082    inputs = rsize;
1083    break;
1084
1085  case Bytecodes::_jsr:
1086  case Bytecodes::_jsr_w:
1087    inputs = 0;
1088    depth  = 1;                  // S.B. depth=1, not zero
1089    break;
1090
1091  default:
1092    // bytecode produces a typed result
1093    inputs = rsize - depth;
1094    assert(inputs >= 0, "");
1095    break;
1096  }
1097
1098#ifdef ASSERT
1099  // spot check
1100  int outputs = depth + inputs;
1101  assert(outputs >= 0, "sanity");
1102  switch (code) {
1103  case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;
1104  case Bytecodes::_athrow:    assert(inputs == 1 && outputs == 0, ""); break;
1105  case Bytecodes::_aload_0:   assert(inputs == 0 && outputs == 1, ""); break;
1106  case Bytecodes::_return:    assert(inputs == 0 && outputs == 0, ""); break;
1107  case Bytecodes::_drem:      assert(inputs == 4 && outputs == 2, ""); break;
1108  }
1109#endif //ASSERT
1110
1111  return true;
1112}
1113
1114
1115
1116//------------------------------basic_plus_adr---------------------------------
1117Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {
1118  // short-circuit a common case
1119  if (offset == intcon(0))  return ptr;
1120  return _gvn.transform( new AddPNode(base, ptr, offset) );
1121}
1122
1123Node* GraphKit::ConvI2L(Node* offset) {
1124  // short-circuit a common case
1125  jint offset_con = find_int_con(offset, Type::OffsetBot);
1126  if (offset_con != Type::OffsetBot) {
1127    return longcon((jlong) offset_con);
1128  }
1129  return _gvn.transform( new ConvI2LNode(offset));
1130}
1131
1132Node* GraphKit::ConvI2UL(Node* offset) {
1133  juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);
1134  if (offset_con != (juint) Type::OffsetBot) {
1135    return longcon((julong) offset_con);
1136  }
1137  Node* conv = _gvn.transform( new ConvI2LNode(offset));
1138  Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1139  return _gvn.transform( new AndLNode(conv, mask) );
1140}
1141
1142Node* GraphKit::ConvL2I(Node* offset) {
1143  // short-circuit a common case
1144  jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1145  if (offset_con != (jlong)Type::OffsetBot) {
1146    return intcon((int) offset_con);
1147  }
1148  return _gvn.transform( new ConvL2INode(offset));
1149}
1150
1151//-------------------------load_object_klass-----------------------------------
1152Node* GraphKit::load_object_klass(Node* obj) {
1153  // Special-case a fresh allocation to avoid building nodes:
1154  Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1155  if (akls != NULL)  return akls;
1156  Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1157  return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1158}
1159
1160//-------------------------load_array_length-----------------------------------
1161Node* GraphKit::load_array_length(Node* array) {
1162  // Special-case a fresh allocation to avoid building nodes:
1163  AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1164  Node *alen;
1165  if (alloc == NULL) {
1166    Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1167    alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1168  } else {
1169    alen = alloc->Ideal_length();
1170    Node* ccast = alloc->make_ideal_length(_gvn.type(array)->is_oopptr(), &_gvn);
1171    if (ccast != alen) {
1172      alen = _gvn.transform(ccast);
1173    }
1174  }
1175  return alen;
1176}
1177
1178//------------------------------do_null_check----------------------------------
1179// Helper function to do a NULL pointer check.  Returned value is
1180// the incoming address with NULL casted away.  You are allowed to use the
1181// not-null value only if you are control dependent on the test.
1182extern int explicit_null_checks_inserted,
1183           explicit_null_checks_elided;
1184Node* GraphKit::null_check_common(Node* value, BasicType type,
1185                                  // optional arguments for variations:
1186                                  bool assert_null,
1187                                  Node* *null_control,
1188                                  bool speculative) {
1189  assert(!assert_null || null_control == NULL, "not both at once");
1190  if (stopped())  return top();
1191  if (!GenerateCompilerNullChecks && !assert_null && null_control == NULL) {
1192    // For some performance testing, we may wish to suppress null checking.
1193    value = cast_not_null(value);   // Make it appear to be non-null (4962416).
1194    return value;
1195  }
1196  explicit_null_checks_inserted++;
1197
1198  // Construct NULL check
1199  Node *chk = NULL;
1200  switch(type) {
1201    case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1202    case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1203    case T_ARRAY  : // fall through
1204      type = T_OBJECT;  // simplify further tests
1205    case T_OBJECT : {
1206      const Type *t = _gvn.type( value );
1207
1208      const TypeOopPtr* tp = t->isa_oopptr();
1209      if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1210          // Only for do_null_check, not any of its siblings:
1211          && !assert_null && null_control == NULL) {
1212        // Usually, any field access or invocation on an unloaded oop type
1213        // will simply fail to link, since the statically linked class is
1214        // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1215        // the static class is loaded but the sharper oop type is not.
1216        // Rather than checking for this obscure case in lots of places,
1217        // we simply observe that a null check on an unloaded class
1218        // will always be followed by a nonsense operation, so we
1219        // can just issue the uncommon trap here.
1220        // Our access to the unloaded class will only be correct
1221        // after it has been loaded and initialized, which requires
1222        // a trip through the interpreter.
1223#ifndef PRODUCT
1224        if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }
1225#endif
1226        uncommon_trap(Deoptimization::Reason_unloaded,
1227                      Deoptimization::Action_reinterpret,
1228                      tp->klass(), "!loaded");
1229        return top();
1230      }
1231
1232      if (assert_null) {
1233        // See if the type is contained in NULL_PTR.
1234        // If so, then the value is already null.
1235        if (t->higher_equal(TypePtr::NULL_PTR)) {
1236          explicit_null_checks_elided++;
1237          return value;           // Elided null assert quickly!
1238        }
1239      } else {
1240        // See if mixing in the NULL pointer changes type.
1241        // If so, then the NULL pointer was not allowed in the original
1242        // type.  In other words, "value" was not-null.
1243        if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {
1244          // same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...
1245          explicit_null_checks_elided++;
1246          return value;           // Elided null check quickly!
1247        }
1248      }
1249      chk = new CmpPNode( value, null() );
1250      break;
1251    }
1252
1253    default:
1254      fatal(err_msg_res("unexpected type: %s", type2name(type)));
1255  }
1256  assert(chk != NULL, "sanity check");
1257  chk = _gvn.transform(chk);
1258
1259  BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;
1260  BoolNode *btst = new BoolNode( chk, btest);
1261  Node   *tst = _gvn.transform( btst );
1262
1263  //-----------
1264  // if peephole optimizations occurred, a prior test existed.
1265  // If a prior test existed, maybe it dominates as we can avoid this test.
1266  if (tst != btst && type == T_OBJECT) {
1267    // At this point we want to scan up the CFG to see if we can
1268    // find an identical test (and so avoid this test altogether).
1269    Node *cfg = control();
1270    int depth = 0;
1271    while( depth < 16 ) {       // Limit search depth for speed
1272      if( cfg->Opcode() == Op_IfTrue &&
1273          cfg->in(0)->in(1) == tst ) {
1274        // Found prior test.  Use "cast_not_null" to construct an identical
1275        // CastPP (and hence hash to) as already exists for the prior test.
1276        // Return that casted value.
1277        if (assert_null) {
1278          replace_in_map(value, null());
1279          return null();  // do not issue the redundant test
1280        }
1281        Node *oldcontrol = control();
1282        set_control(cfg);
1283        Node *res = cast_not_null(value);
1284        set_control(oldcontrol);
1285        explicit_null_checks_elided++;
1286        return res;
1287      }
1288      cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1289      if (cfg == NULL)  break;  // Quit at region nodes
1290      depth++;
1291    }
1292  }
1293
1294  //-----------
1295  // Branch to failure if null
1296  float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1297  Deoptimization::DeoptReason reason;
1298  if (assert_null) {
1299    reason = Deoptimization::Reason_null_assert;
1300  } else if (type == T_OBJECT) {
1301    reason = Deoptimization::reason_null_check(speculative);
1302  } else {
1303    reason = Deoptimization::Reason_div0_check;
1304  }
1305  // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1306  // ciMethodData::has_trap_at will return a conservative -1 if any
1307  // must-be-null assertion has failed.  This could cause performance
1308  // problems for a method after its first do_null_assert failure.
1309  // Consider using 'Reason_class_check' instead?
1310
1311  // To cause an implicit null check, we set the not-null probability
1312  // to the maximum (PROB_MAX).  For an explicit check the probability
1313  // is set to a smaller value.
1314  if (null_control != NULL || too_many_traps(reason)) {
1315    // probability is less likely
1316    ok_prob =  PROB_LIKELY_MAG(3);
1317  } else if (!assert_null &&
1318             (ImplicitNullCheckThreshold > 0) &&
1319             method() != NULL &&
1320             (method()->method_data()->trap_count(reason)
1321              >= (uint)ImplicitNullCheckThreshold)) {
1322    ok_prob =  PROB_LIKELY_MAG(3);
1323  }
1324
1325  if (null_control != NULL) {
1326    IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);
1327    Node* null_true = _gvn.transform( new IfFalseNode(iff));
1328    set_control(      _gvn.transform( new IfTrueNode(iff)));
1329    if (null_true == top())
1330      explicit_null_checks_elided++;
1331    (*null_control) = null_true;
1332  } else {
1333    BuildCutout unless(this, tst, ok_prob);
1334    // Check for optimizer eliding test at parse time
1335    if (stopped()) {
1336      // Failure not possible; do not bother making uncommon trap.
1337      explicit_null_checks_elided++;
1338    } else if (assert_null) {
1339      uncommon_trap(reason,
1340                    Deoptimization::Action_make_not_entrant,
1341                    NULL, "assert_null");
1342    } else {
1343      replace_in_map(value, zerocon(type));
1344      builtin_throw(reason);
1345    }
1346  }
1347
1348  // Must throw exception, fall-thru not possible?
1349  if (stopped()) {
1350    return top();               // No result
1351  }
1352
1353  if (assert_null) {
1354    // Cast obj to null on this path.
1355    replace_in_map(value, zerocon(type));
1356    return zerocon(type);
1357  }
1358
1359  // Cast obj to not-null on this path, if there is no null_control.
1360  // (If there is a null_control, a non-null value may come back to haunt us.)
1361  if (type == T_OBJECT) {
1362    Node* cast = cast_not_null(value, false);
1363    if (null_control == NULL || (*null_control) == top())
1364      replace_in_map(value, cast);
1365    value = cast;
1366  }
1367
1368  return value;
1369}
1370
1371
1372//------------------------------cast_not_null----------------------------------
1373// Cast obj to not-null on this path
1374Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1375  const Type *t = _gvn.type(obj);
1376  const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1377  // Object is already not-null?
1378  if( t == t_not_null ) return obj;
1379
1380  Node *cast = new CastPPNode(obj,t_not_null);
1381  cast->init_req(0, control());
1382  cast = _gvn.transform( cast );
1383
1384  // Scan for instances of 'obj' in the current JVM mapping.
1385  // These instances are known to be not-null after the test.
1386  if (do_replace_in_map)
1387    replace_in_map(obj, cast);
1388
1389  return cast;                  // Return casted value
1390}
1391
1392
1393//--------------------------replace_in_map-------------------------------------
1394void GraphKit::replace_in_map(Node* old, Node* neww) {
1395  if (old == neww) {
1396    return;
1397  }
1398
1399  map()->replace_edge(old, neww);
1400
1401  // Note: This operation potentially replaces any edge
1402  // on the map.  This includes locals, stack, and monitors
1403  // of the current (innermost) JVM state.
1404
1405  // don't let inconsistent types from profiling escape this
1406  // method
1407
1408  const Type* told = _gvn.type(old);
1409  const Type* tnew = _gvn.type(neww);
1410
1411  if (!tnew->higher_equal(told)) {
1412    return;
1413  }
1414
1415  map()->record_replaced_node(old, neww);
1416}
1417
1418
1419//=============================================================================
1420//--------------------------------memory---------------------------------------
1421Node* GraphKit::memory(uint alias_idx) {
1422  MergeMemNode* mem = merged_memory();
1423  Node* p = mem->memory_at(alias_idx);
1424  _gvn.set_type(p, Type::MEMORY);  // must be mapped
1425  return p;
1426}
1427
1428//-----------------------------reset_memory------------------------------------
1429Node* GraphKit::reset_memory() {
1430  Node* mem = map()->memory();
1431  // do not use this node for any more parsing!
1432  debug_only( map()->set_memory((Node*)NULL) );
1433  return _gvn.transform( mem );
1434}
1435
1436//------------------------------set_all_memory---------------------------------
1437void GraphKit::set_all_memory(Node* newmem) {
1438  Node* mergemem = MergeMemNode::make(newmem);
1439  gvn().set_type_bottom(mergemem);
1440  map()->set_memory(mergemem);
1441}
1442
1443//------------------------------set_all_memory_call----------------------------
1444void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {
1445  Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );
1446  set_all_memory(newmem);
1447}
1448
1449//=============================================================================
1450//
1451// parser factory methods for MemNodes
1452//
1453// These are layered on top of the factory methods in LoadNode and StoreNode,
1454// and integrate with the parser's memory state and _gvn engine.
1455//
1456
1457// factory methods in "int adr_idx"
1458Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1459                          int adr_idx,
1460                          MemNode::MemOrd mo, bool require_atomic_access) {
1461  assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1462  const TypePtr* adr_type = NULL; // debug-mode-only argument
1463  debug_only(adr_type = C->get_adr_type(adr_idx));
1464  Node* mem = memory(adr_idx);
1465  Node* ld;
1466  if (require_atomic_access && bt == T_LONG) {
1467    ld = LoadLNode::make_atomic(ctl, mem, adr, adr_type, t, mo);
1468  } else if (require_atomic_access && bt == T_DOUBLE) {
1469    ld = LoadDNode::make_atomic(ctl, mem, adr, adr_type, t, mo);
1470  } else {
1471    ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo);
1472  }
1473  ld = _gvn.transform(ld);
1474  if ((bt == T_OBJECT) && C->do_escape_analysis() || C->eliminate_boxing()) {
1475    // Improve graph before escape analysis and boxing elimination.
1476    record_for_igvn(ld);
1477  }
1478  return ld;
1479}
1480
1481Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1482                                int adr_idx,
1483                                MemNode::MemOrd mo,
1484                                bool require_atomic_access) {
1485  assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1486  const TypePtr* adr_type = NULL;
1487  debug_only(adr_type = C->get_adr_type(adr_idx));
1488  Node *mem = memory(adr_idx);
1489  Node* st;
1490  if (require_atomic_access && bt == T_LONG) {
1491    st = StoreLNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1492  } else if (require_atomic_access && bt == T_DOUBLE) {
1493    st = StoreDNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1494  } else {
1495    st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);
1496  }
1497  st = _gvn.transform(st);
1498  set_memory(st, adr_idx);
1499  // Back-to-back stores can only remove intermediate store with DU info
1500  // so push on worklist for optimizer.
1501  if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1502    record_for_igvn(st);
1503
1504  return st;
1505}
1506
1507
1508void GraphKit::pre_barrier(bool do_load,
1509                           Node* ctl,
1510                           Node* obj,
1511                           Node* adr,
1512                           uint  adr_idx,
1513                           Node* val,
1514                           const TypeOopPtr* val_type,
1515                           Node* pre_val,
1516                           BasicType bt) {
1517
1518  BarrierSet* bs = Universe::heap()->barrier_set();
1519  set_control(ctl);
1520  switch (bs->kind()) {
1521    case BarrierSet::G1SATBCTLogging:
1522      g1_write_barrier_pre(do_load, obj, adr, adr_idx, val, val_type, pre_val, bt);
1523      break;
1524
1525    case BarrierSet::CardTableModRef:
1526    case BarrierSet::CardTableExtension:
1527    case BarrierSet::ModRef:
1528      break;
1529
1530    default      :
1531      ShouldNotReachHere();
1532
1533  }
1534}
1535
1536bool GraphKit::can_move_pre_barrier() const {
1537  BarrierSet* bs = Universe::heap()->barrier_set();
1538  switch (bs->kind()) {
1539    case BarrierSet::G1SATBCTLogging:
1540      return true; // Can move it if no safepoint
1541
1542    case BarrierSet::CardTableModRef:
1543    case BarrierSet::CardTableExtension:
1544    case BarrierSet::ModRef:
1545      return true; // There is no pre-barrier
1546
1547    default      :
1548      ShouldNotReachHere();
1549  }
1550  return false;
1551}
1552
1553void GraphKit::post_barrier(Node* ctl,
1554                            Node* store,
1555                            Node* obj,
1556                            Node* adr,
1557                            uint  adr_idx,
1558                            Node* val,
1559                            BasicType bt,
1560                            bool use_precise) {
1561  BarrierSet* bs = Universe::heap()->barrier_set();
1562  set_control(ctl);
1563  switch (bs->kind()) {
1564    case BarrierSet::G1SATBCTLogging:
1565      g1_write_barrier_post(store, obj, adr, adr_idx, val, bt, use_precise);
1566      break;
1567
1568    case BarrierSet::CardTableModRef:
1569    case BarrierSet::CardTableExtension:
1570      write_barrier_post(store, obj, adr, adr_idx, val, use_precise);
1571      break;
1572
1573    case BarrierSet::ModRef:
1574      break;
1575
1576    default      :
1577      ShouldNotReachHere();
1578
1579  }
1580}
1581
1582Node* GraphKit::store_oop(Node* ctl,
1583                          Node* obj,
1584                          Node* adr,
1585                          const TypePtr* adr_type,
1586                          Node* val,
1587                          const TypeOopPtr* val_type,
1588                          BasicType bt,
1589                          bool use_precise,
1590                          MemNode::MemOrd mo) {
1591  // Transformation of a value which could be NULL pointer (CastPP #NULL)
1592  // could be delayed during Parse (for example, in adjust_map_after_if()).
1593  // Execute transformation here to avoid barrier generation in such case.
1594  if (_gvn.type(val) == TypePtr::NULL_PTR)
1595    val = _gvn.makecon(TypePtr::NULL_PTR);
1596
1597  set_control(ctl);
1598  if (stopped()) return top(); // Dead path ?
1599
1600  assert(bt == T_OBJECT, "sanity");
1601  assert(val != NULL, "not dead path");
1602  uint adr_idx = C->get_alias_index(adr_type);
1603  assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1604
1605  pre_barrier(true /* do_load */,
1606              control(), obj, adr, adr_idx, val, val_type,
1607              NULL /* pre_val */,
1608              bt);
1609
1610  Node* store = store_to_memory(control(), adr, val, bt, adr_idx, mo);
1611  post_barrier(control(), store, obj, adr, adr_idx, val, bt, use_precise);
1612  return store;
1613}
1614
1615// Could be an array or object we don't know at compile time (unsafe ref.)
1616Node* GraphKit::store_oop_to_unknown(Node* ctl,
1617                             Node* obj,   // containing obj
1618                             Node* adr,  // actual adress to store val at
1619                             const TypePtr* adr_type,
1620                             Node* val,
1621                             BasicType bt,
1622                             MemNode::MemOrd mo) {
1623  Compile::AliasType* at = C->alias_type(adr_type);
1624  const TypeOopPtr* val_type = NULL;
1625  if (adr_type->isa_instptr()) {
1626    if (at->field() != NULL) {
1627      // known field.  This code is a copy of the do_put_xxx logic.
1628      ciField* field = at->field();
1629      if (!field->type()->is_loaded()) {
1630        val_type = TypeInstPtr::BOTTOM;
1631      } else {
1632        val_type = TypeOopPtr::make_from_klass(field->type()->as_klass());
1633      }
1634    }
1635  } else if (adr_type->isa_aryptr()) {
1636    val_type = adr_type->is_aryptr()->elem()->make_oopptr();
1637  }
1638  if (val_type == NULL) {
1639    val_type = TypeInstPtr::BOTTOM;
1640  }
1641  return store_oop(ctl, obj, adr, adr_type, val, val_type, bt, true, mo);
1642}
1643
1644
1645//-------------------------array_element_address-------------------------
1646Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1647                                      const TypeInt* sizetype) {
1648  uint shift  = exact_log2(type2aelembytes(elembt));
1649  uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1650
1651  // short-circuit a common case (saves lots of confusing waste motion)
1652  jint idx_con = find_int_con(idx, -1);
1653  if (idx_con >= 0) {
1654    intptr_t offset = header + ((intptr_t)idx_con << shift);
1655    return basic_plus_adr(ary, offset);
1656  }
1657
1658  // must be correct type for alignment purposes
1659  Node* base  = basic_plus_adr(ary, header);
1660  idx = Compile::conv_I2X_index(&_gvn, idx, sizetype);
1661  Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1662  return basic_plus_adr(ary, base, scale);
1663}
1664
1665//-------------------------load_array_element-------------------------
1666Node* GraphKit::load_array_element(Node* ctl, Node* ary, Node* idx, const TypeAryPtr* arytype) {
1667  const Type* elemtype = arytype->elem();
1668  BasicType elembt = elemtype->array_element_basic_type();
1669  Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1670  Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
1671  return ld;
1672}
1673
1674//-------------------------set_arguments_for_java_call-------------------------
1675// Arguments (pre-popped from the stack) are taken from the JVMS.
1676void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1677  // Add the call arguments:
1678  uint nargs = call->method()->arg_size();
1679  for (uint i = 0; i < nargs; i++) {
1680    Node* arg = argument(i);
1681    call->init_req(i + TypeFunc::Parms, arg);
1682  }
1683}
1684
1685//---------------------------set_edges_for_java_call---------------------------
1686// Connect a newly created call into the current JVMS.
1687// A return value node (if any) is returned from set_edges_for_java_call.
1688void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1689
1690  // Add the predefined inputs:
1691  call->init_req( TypeFunc::Control, control() );
1692  call->init_req( TypeFunc::I_O    , i_o() );
1693  call->init_req( TypeFunc::Memory , reset_memory() );
1694  call->init_req( TypeFunc::FramePtr, frameptr() );
1695  call->init_req( TypeFunc::ReturnAdr, top() );
1696
1697  add_safepoint_edges(call, must_throw);
1698
1699  Node* xcall = _gvn.transform(call);
1700
1701  if (xcall == top()) {
1702    set_control(top());
1703    return;
1704  }
1705  assert(xcall == call, "call identity is stable");
1706
1707  // Re-use the current map to produce the result.
1708
1709  set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1710  set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1711  set_all_memory_call(xcall, separate_io_proj);
1712
1713  //return xcall;   // no need, caller already has it
1714}
1715
1716Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj) {
1717  if (stopped())  return top();  // maybe the call folded up?
1718
1719  // Capture the return value, if any.
1720  Node* ret;
1721  if (call->method() == NULL ||
1722      call->method()->return_type()->basic_type() == T_VOID)
1723        ret = top();
1724  else  ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1725
1726  // Note:  Since any out-of-line call can produce an exception,
1727  // we always insert an I_O projection from the call into the result.
1728
1729  make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj);
1730
1731  if (separate_io_proj) {
1732    // The caller requested separate projections be used by the fall
1733    // through and exceptional paths, so replace the projections for
1734    // the fall through path.
1735    set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1736    set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1737  }
1738  return ret;
1739}
1740
1741//--------------------set_predefined_input_for_runtime_call--------------------
1742// Reading and setting the memory state is way conservative here.
1743// The real problem is that I am not doing real Type analysis on memory,
1744// so I cannot distinguish card mark stores from other stores.  Across a GC
1745// point the Store Barrier and the card mark memory has to agree.  I cannot
1746// have a card mark store and its barrier split across the GC point from
1747// either above or below.  Here I get that to happen by reading ALL of memory.
1748// A better answer would be to separate out card marks from other memory.
1749// For now, return the input memory state, so that it can be reused
1750// after the call, if this call has restricted memory effects.
1751Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call) {
1752  // Set fixed predefined input arguments
1753  Node* memory = reset_memory();
1754  call->init_req( TypeFunc::Control,   control()  );
1755  call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1756  call->init_req( TypeFunc::Memory,    memory     ); // may gc ptrs
1757  call->init_req( TypeFunc::FramePtr,  frameptr() );
1758  call->init_req( TypeFunc::ReturnAdr, top()      );
1759  return memory;
1760}
1761
1762//-------------------set_predefined_output_for_runtime_call--------------------
1763// Set control and memory (not i_o) from the call.
1764// If keep_mem is not NULL, use it for the output state,
1765// except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
1766// If hook_mem is NULL, this call produces no memory effects at all.
1767// If hook_mem is a Java-visible memory slice (such as arraycopy operands),
1768// then only that memory slice is taken from the call.
1769// In the last case, we must put an appropriate memory barrier before
1770// the call, so as to create the correct anti-dependencies on loads
1771// preceding the call.
1772void GraphKit::set_predefined_output_for_runtime_call(Node* call,
1773                                                      Node* keep_mem,
1774                                                      const TypePtr* hook_mem) {
1775  // no i/o
1776  set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
1777  if (keep_mem) {
1778    // First clone the existing memory state
1779    set_all_memory(keep_mem);
1780    if (hook_mem != NULL) {
1781      // Make memory for the call
1782      Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
1783      // Set the RawPtr memory state only.  This covers all the heap top/GC stuff
1784      // We also use hook_mem to extract specific effects from arraycopy stubs.
1785      set_memory(mem, hook_mem);
1786    }
1787    // ...else the call has NO memory effects.
1788
1789    // Make sure the call advertises its memory effects precisely.
1790    // This lets us build accurate anti-dependences in gcm.cpp.
1791    assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
1792           "call node must be constructed correctly");
1793  } else {
1794    assert(hook_mem == NULL, "");
1795    // This is not a "slow path" call; all memory comes from the call.
1796    set_all_memory_call(call);
1797  }
1798}
1799
1800
1801// Replace the call with the current state of the kit.
1802void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1803  JVMState* ejvms = NULL;
1804  if (has_exceptions()) {
1805    ejvms = transfer_exceptions_into_jvms();
1806  }
1807
1808  ReplacedNodes replaced_nodes = map()->replaced_nodes();
1809  ReplacedNodes replaced_nodes_exception;
1810  Node* ex_ctl = top();
1811
1812  SafePointNode* final_state = stop();
1813
1814  // Find all the needed outputs of this call
1815  CallProjections callprojs;
1816  call->extract_projections(&callprojs, true);
1817
1818  Node* init_mem = call->in(TypeFunc::Memory);
1819  Node* final_mem = final_state->in(TypeFunc::Memory);
1820  Node* final_ctl = final_state->in(TypeFunc::Control);
1821  Node* final_io = final_state->in(TypeFunc::I_O);
1822
1823  // Replace all the old call edges with the edges from the inlining result
1824  if (callprojs.fallthrough_catchproj != NULL) {
1825    C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1826  }
1827  if (callprojs.fallthrough_memproj != NULL) {
1828    if (final_mem->is_MergeMem()) {
1829      // Parser's exits MergeMem was not transformed but may be optimized
1830      final_mem = _gvn.transform(final_mem);
1831    }
1832    C->gvn_replace_by(callprojs.fallthrough_memproj,   final_mem);
1833  }
1834  if (callprojs.fallthrough_ioproj != NULL) {
1835    C->gvn_replace_by(callprojs.fallthrough_ioproj,    final_io);
1836  }
1837
1838  // Replace the result with the new result if it exists and is used
1839  if (callprojs.resproj != NULL && result != NULL) {
1840    C->gvn_replace_by(callprojs.resproj, result);
1841  }
1842
1843  if (ejvms == NULL) {
1844    // No exception edges to simply kill off those paths
1845    if (callprojs.catchall_catchproj != NULL) {
1846      C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1847    }
1848    if (callprojs.catchall_memproj != NULL) {
1849      C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
1850    }
1851    if (callprojs.catchall_ioproj != NULL) {
1852      C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
1853    }
1854    // Replace the old exception object with top
1855    if (callprojs.exobj != NULL) {
1856      C->gvn_replace_by(callprojs.exobj, C->top());
1857    }
1858  } else {
1859    GraphKit ekit(ejvms);
1860
1861    // Load my combined exception state into the kit, with all phis transformed:
1862    SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1863    replaced_nodes_exception = ex_map->replaced_nodes();
1864
1865    Node* ex_oop = ekit.use_exception_state(ex_map);
1866
1867    if (callprojs.catchall_catchproj != NULL) {
1868      C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1869      ex_ctl = ekit.control();
1870    }
1871    if (callprojs.catchall_memproj != NULL) {
1872      C->gvn_replace_by(callprojs.catchall_memproj,   ekit.reset_memory());
1873    }
1874    if (callprojs.catchall_ioproj != NULL) {
1875      C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
1876    }
1877
1878    // Replace the old exception object with the newly created one
1879    if (callprojs.exobj != NULL) {
1880      C->gvn_replace_by(callprojs.exobj, ex_oop);
1881    }
1882  }
1883
1884  // Disconnect the call from the graph
1885  call->disconnect_inputs(NULL, C);
1886  C->gvn_replace_by(call, C->top());
1887
1888  // Clean up any MergeMems that feed other MergeMems since the
1889  // optimizer doesn't like that.
1890  if (final_mem->is_MergeMem()) {
1891    Node_List wl;
1892    for (SimpleDUIterator i(final_mem); i.has_next(); i.next()) {
1893      Node* m = i.get();
1894      if (m->is_MergeMem() && !wl.contains(m)) {
1895        wl.push(m);
1896      }
1897    }
1898    while (wl.size()  > 0) {
1899      _gvn.transform(wl.pop());
1900    }
1901  }
1902
1903  if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
1904    replaced_nodes.apply(C, final_ctl);
1905  }
1906  if (!ex_ctl->is_top() && do_replaced_nodes) {
1907    replaced_nodes_exception.apply(C, ex_ctl);
1908  }
1909}
1910
1911
1912//------------------------------increment_counter------------------------------
1913// for statistics: increment a VM counter by 1
1914
1915void GraphKit::increment_counter(address counter_addr) {
1916  Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
1917  increment_counter(adr1);
1918}
1919
1920void GraphKit::increment_counter(Node* counter_addr) {
1921  int adr_type = Compile::AliasIdxRaw;
1922  Node* ctrl = control();
1923  Node* cnt  = make_load(ctrl, counter_addr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
1924  Node* incr = _gvn.transform(new AddINode(cnt, _gvn.intcon(1)));
1925  store_to_memory(ctrl, counter_addr, incr, T_INT, adr_type, MemNode::unordered);
1926}
1927
1928
1929//------------------------------uncommon_trap----------------------------------
1930// Bail out to the interpreter in mid-method.  Implemented by calling the
1931// uncommon_trap blob.  This helper function inserts a runtime call with the
1932// right debug info.
1933void GraphKit::uncommon_trap(int trap_request,
1934                             ciKlass* klass, const char* comment,
1935                             bool must_throw,
1936                             bool keep_exact_action) {
1937  if (failing())  stop();
1938  if (stopped())  return; // trap reachable?
1939
1940  // Note:  If ProfileTraps is true, and if a deopt. actually
1941  // occurs here, the runtime will make sure an MDO exists.  There is
1942  // no need to call method()->ensure_method_data() at this point.
1943
1944  // Set the stack pointer to the right value for reexecution:
1945  set_sp(reexecute_sp());
1946
1947#ifdef ASSERT
1948  if (!must_throw) {
1949    // Make sure the stack has at least enough depth to execute
1950    // the current bytecode.
1951    int inputs, ignored_depth;
1952    if (compute_stack_effects(inputs, ignored_depth)) {
1953      assert(sp() >= inputs, err_msg_res("must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
1954             Bytecodes::name(java_bc()), sp(), inputs));
1955    }
1956  }
1957#endif
1958
1959  Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1960  Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
1961
1962  switch (action) {
1963  case Deoptimization::Action_maybe_recompile:
1964  case Deoptimization::Action_reinterpret:
1965    // Temporary fix for 6529811 to allow virtual calls to be sure they
1966    // get the chance to go from mono->bi->mega
1967    if (!keep_exact_action &&
1968        Deoptimization::trap_request_index(trap_request) < 0 &&
1969        too_many_recompiles(reason)) {
1970      // This BCI is causing too many recompilations.
1971      if (C->log() != NULL) {
1972        C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
1973                Deoptimization::trap_reason_name(reason),
1974                Deoptimization::trap_action_name(action));
1975      }
1976      action = Deoptimization::Action_none;
1977      trap_request = Deoptimization::make_trap_request(reason, action);
1978    } else {
1979      C->set_trap_can_recompile(true);
1980    }
1981    break;
1982  case Deoptimization::Action_make_not_entrant:
1983    C->set_trap_can_recompile(true);
1984    break;
1985#ifdef ASSERT
1986  case Deoptimization::Action_none:
1987  case Deoptimization::Action_make_not_compilable:
1988    break;
1989  default:
1990    fatal(err_msg_res("unknown action %d: %s", action, Deoptimization::trap_action_name(action)));
1991    break;
1992#endif
1993  }
1994
1995  if (TraceOptoParse) {
1996    char buf[100];
1997    tty->print_cr("Uncommon trap %s at bci:%d",
1998                  Deoptimization::format_trap_request(buf, sizeof(buf),
1999                                                      trap_request), bci());
2000  }
2001
2002  CompileLog* log = C->log();
2003  if (log != NULL) {
2004    int kid = (klass == NULL)? -1: log->identify(klass);
2005    log->begin_elem("uncommon_trap bci='%d'", bci());
2006    char buf[100];
2007    log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2008                                                          trap_request));
2009    if (kid >= 0)         log->print(" klass='%d'", kid);
2010    if (comment != NULL)  log->print(" comment='%s'", comment);
2011    log->end_elem();
2012  }
2013
2014  // Make sure any guarding test views this path as very unlikely
2015  Node *i0 = control()->in(0);
2016  if (i0 != NULL && i0->is_If()) {        // Found a guarding if test?
2017    IfNode *iff = i0->as_If();
2018    float f = iff->_prob;   // Get prob
2019    if (control()->Opcode() == Op_IfTrue) {
2020      if (f > PROB_UNLIKELY_MAG(4))
2021        iff->_prob = PROB_MIN;
2022    } else {
2023      if (f < PROB_LIKELY_MAG(4))
2024        iff->_prob = PROB_MAX;
2025    }
2026  }
2027
2028  // Clear out dead values from the debug info.
2029  kill_dead_locals();
2030
2031  // Now insert the uncommon trap subroutine call
2032  address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2033  const TypePtr* no_memory_effects = NULL;
2034  // Pass the index of the class to be loaded
2035  Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2036                                 (must_throw ? RC_MUST_THROW : 0),
2037                                 OptoRuntime::uncommon_trap_Type(),
2038                                 call_addr, "uncommon_trap", no_memory_effects,
2039                                 intcon(trap_request));
2040  assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2041         "must extract request correctly from the graph");
2042  assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2043
2044  call->set_req(TypeFunc::ReturnAdr, returnadr());
2045  // The debug info is the only real input to this call.
2046
2047  // Halt-and-catch fire here.  The above call should never return!
2048  HaltNode* halt = new HaltNode(control(), frameptr());
2049  _gvn.set_type_bottom(halt);
2050  root()->add_req(halt);
2051
2052  stop_and_kill_map();
2053}
2054
2055
2056//--------------------------just_allocated_object------------------------------
2057// Report the object that was just allocated.
2058// It must be the case that there are no intervening safepoints.
2059// We use this to determine if an object is so "fresh" that
2060// it does not require card marks.
2061Node* GraphKit::just_allocated_object(Node* current_control) {
2062  if (C->recent_alloc_ctl() == current_control)
2063    return C->recent_alloc_obj();
2064  return NULL;
2065}
2066
2067
2068void GraphKit::round_double_arguments(ciMethod* dest_method) {
2069  // (Note:  TypeFunc::make has a cache that makes this fast.)
2070  const TypeFunc* tf    = TypeFunc::make(dest_method);
2071  int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2072  for (int j = 0; j < nargs; j++) {
2073    const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2074    if( targ->basic_type() == T_DOUBLE ) {
2075      // If any parameters are doubles, they must be rounded before
2076      // the call, dstore_rounding does gvn.transform
2077      Node *arg = argument(j);
2078      arg = dstore_rounding(arg);
2079      set_argument(j, arg);
2080    }
2081  }
2082}
2083
2084/**
2085 * Record profiling data exact_kls for Node n with the type system so
2086 * that it can propagate it (speculation)
2087 *
2088 * @param n          node that the type applies to
2089 * @param exact_kls  type from profiling
2090 * @param maybe_null did profiling see null?
2091 *
2092 * @return           node with improved type
2093 */
2094Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, bool maybe_null) {
2095  const Type* current_type = _gvn.type(n);
2096  assert(UseTypeSpeculation, "type speculation must be on");
2097
2098  const TypePtr* speculative = current_type->speculative();
2099
2100  // Should the klass from the profile be recorded in the speculative type?
2101  if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2102    const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2103    const TypeOopPtr* xtype = tklass->as_instance_type();
2104    assert(xtype->klass_is_exact(), "Should be exact");
2105    // Any reason to believe n is not null (from this profiling or a previous one)?
2106    const TypePtr* ptr = (maybe_null && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2107    // record the new speculative type's depth
2108    speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2109    speculative = speculative->with_inline_depth(jvms()->depth());
2110  } else if (current_type->would_improve_ptr(maybe_null)) {
2111    // Profiling report that null was never seen so we can change the
2112    // speculative type to non null ptr.
2113    assert(!maybe_null, "nothing to improve");
2114    if (speculative == NULL) {
2115      speculative = TypePtr::NOTNULL;
2116    } else {
2117      const TypePtr* ptr = TypePtr::NOTNULL;
2118      speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2119    }
2120  }
2121
2122  if (speculative != current_type->speculative()) {
2123    // Build a type with a speculative type (what we think we know
2124    // about the type but will need a guard when we use it)
2125    const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2126    // We're changing the type, we need a new CheckCast node to carry
2127    // the new type. The new type depends on the control: what
2128    // profiling tells us is only valid from here as far as we can
2129    // tell.
2130    Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2131    cast = _gvn.transform(cast);
2132    replace_in_map(n, cast);
2133    n = cast;
2134  }
2135
2136  return n;
2137}
2138
2139/**
2140 * Record profiling data from receiver profiling at an invoke with the
2141 * type system so that it can propagate it (speculation)
2142 *
2143 * @param n  receiver node
2144 *
2145 * @return   node with improved type
2146 */
2147Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2148  if (!UseTypeSpeculation) {
2149    return n;
2150  }
2151  ciKlass* exact_kls = profile_has_unique_klass();
2152  bool maybe_null = true;
2153  if (java_bc() == Bytecodes::_checkcast ||
2154      java_bc() == Bytecodes::_instanceof ||
2155      java_bc() == Bytecodes::_aastore) {
2156    ciProfileData* data = method()->method_data()->bci_to_data(bci());
2157    bool maybe_null = data == NULL ? true : data->as_BitData()->null_seen();
2158  }
2159  return record_profile_for_speculation(n, exact_kls, maybe_null);
2160  return n;
2161}
2162
2163/**
2164 * Record profiling data from argument profiling at an invoke with the
2165 * type system so that it can propagate it (speculation)
2166 *
2167 * @param dest_method  target method for the call
2168 * @param bc           what invoke bytecode is this?
2169 */
2170void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2171  if (!UseTypeSpeculation) {
2172    return;
2173  }
2174  const TypeFunc* tf    = TypeFunc::make(dest_method);
2175  int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2176  int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2177  for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2178    const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2179    if (targ->basic_type() == T_OBJECT || targ->basic_type() == T_ARRAY) {
2180      bool maybe_null = true;
2181      ciKlass* better_type = NULL;
2182      if (method()->argument_profiled_type(bci(), i, better_type, maybe_null)) {
2183        record_profile_for_speculation(argument(j), better_type, maybe_null);
2184      }
2185      i++;
2186    }
2187  }
2188}
2189
2190/**
2191 * Record profiling data from parameter profiling at an invoke with
2192 * the type system so that it can propagate it (speculation)
2193 */
2194void GraphKit::record_profiled_parameters_for_speculation() {
2195  if (!UseTypeSpeculation) {
2196    return;
2197  }
2198  for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2199    if (_gvn.type(local(i))->isa_oopptr()) {
2200      bool maybe_null = true;
2201      ciKlass* better_type = NULL;
2202      if (method()->parameter_profiled_type(j, better_type, maybe_null)) {
2203        record_profile_for_speculation(local(i), better_type, maybe_null);
2204      }
2205      j++;
2206    }
2207  }
2208}
2209
2210/**
2211 * Record profiling data from return value profiling at an invoke with
2212 * the type system so that it can propagate it (speculation)
2213 */
2214void GraphKit::record_profiled_return_for_speculation() {
2215  if (!UseTypeSpeculation) {
2216    return;
2217  }
2218  bool maybe_null = true;
2219  ciKlass* better_type = NULL;
2220  if (method()->return_profiled_type(bci(), better_type, maybe_null)) {
2221    // If profiling reports a single type for the return value,
2222    // feed it to the type system so it can propagate it as a
2223    // speculative type
2224    record_profile_for_speculation(stack(sp()-1), better_type, maybe_null);
2225  }
2226}
2227
2228void GraphKit::round_double_result(ciMethod* dest_method) {
2229  // A non-strict method may return a double value which has an extended
2230  // exponent, but this must not be visible in a caller which is 'strict'
2231  // If a strict caller invokes a non-strict callee, round a double result
2232
2233  BasicType result_type = dest_method->return_type()->basic_type();
2234  assert( method() != NULL, "must have caller context");
2235  if( result_type == T_DOUBLE && method()->is_strict() && !dest_method->is_strict() ) {
2236    // Destination method's return value is on top of stack
2237    // dstore_rounding() does gvn.transform
2238    Node *result = pop_pair();
2239    result = dstore_rounding(result);
2240    push_pair(result);
2241  }
2242}
2243
2244// rounding for strict float precision conformance
2245Node* GraphKit::precision_rounding(Node* n) {
2246  return UseStrictFP && _method->flags().is_strict()
2247    && UseSSE == 0 && Matcher::strict_fp_requires_explicit_rounding
2248    ? _gvn.transform( new RoundFloatNode(0, n) )
2249    : n;
2250}
2251
2252// rounding for strict double precision conformance
2253Node* GraphKit::dprecision_rounding(Node *n) {
2254  return UseStrictFP && _method->flags().is_strict()
2255    && UseSSE <= 1 && Matcher::strict_fp_requires_explicit_rounding
2256    ? _gvn.transform( new RoundDoubleNode(0, n) )
2257    : n;
2258}
2259
2260// rounding for non-strict double stores
2261Node* GraphKit::dstore_rounding(Node* n) {
2262  return Matcher::strict_fp_requires_explicit_rounding
2263    && UseSSE <= 1
2264    ? _gvn.transform( new RoundDoubleNode(0, n) )
2265    : n;
2266}
2267
2268//=============================================================================
2269// Generate a fast path/slow path idiom.  Graph looks like:
2270// [foo] indicates that 'foo' is a parameter
2271//
2272//              [in]     NULL
2273//                 \    /
2274//                  CmpP
2275//                  Bool ne
2276//                   If
2277//                  /  \
2278//              True    False-<2>
2279//              / |
2280//             /  cast_not_null
2281//           Load  |    |   ^
2282//        [fast_test]   |   |
2283// gvn to   opt_test    |   |
2284//          /    \      |  <1>
2285//      True     False  |
2286//        |         \\  |
2287//   [slow_call]     \[fast_result]
2288//    Ctl   Val       \      \
2289//     |               \      \
2290//    Catch       <1>   \      \
2291//   /    \        ^     \      \
2292//  Ex    No_Ex    |      \      \
2293//  |       \   \  |       \ <2>  \
2294//  ...      \  [slow_res] |  |    \   [null_result]
2295//            \         \--+--+---  |  |
2296//             \           | /    \ | /
2297//              --------Region     Phi
2298//
2299//=============================================================================
2300// Code is structured as a series of driver functions all called 'do_XXX' that
2301// call a set of helper functions.  Helper functions first, then drivers.
2302
2303//------------------------------null_check_oop---------------------------------
2304// Null check oop.  Set null-path control into Region in slot 3.
2305// Make a cast-not-nullness use the other not-null control.  Return cast.
2306Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2307                               bool never_see_null,
2308                               bool safe_for_replace,
2309                               bool speculative) {
2310  // Initial NULL check taken path
2311  (*null_control) = top();
2312  Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2313
2314  // Generate uncommon_trap:
2315  if (never_see_null && (*null_control) != top()) {
2316    // If we see an unexpected null at a check-cast we record it and force a
2317    // recompile; the offending check-cast will be compiled to handle NULLs.
2318    // If we see more than one offending BCI, then all checkcasts in the
2319    // method will be compiled to handle NULLs.
2320    PreserveJVMState pjvms(this);
2321    set_control(*null_control);
2322    replace_in_map(value, null());
2323    Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2324    uncommon_trap(reason,
2325                  Deoptimization::Action_make_not_entrant);
2326    (*null_control) = top();    // NULL path is dead
2327  }
2328  if ((*null_control) == top() && safe_for_replace) {
2329    replace_in_map(value, cast);
2330  }
2331
2332  // Cast away null-ness on the result
2333  return cast;
2334}
2335
2336//------------------------------opt_iff----------------------------------------
2337// Optimize the fast-check IfNode.  Set the fast-path region slot 2.
2338// Return slow-path control.
2339Node* GraphKit::opt_iff(Node* region, Node* iff) {
2340  IfNode *opt_iff = _gvn.transform(iff)->as_If();
2341
2342  // Fast path taken; set region slot 2
2343  Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2344  region->init_req(2,fast_taken); // Capture fast-control
2345
2346  // Fast path not-taken, i.e. slow path
2347  Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2348  return slow_taken;
2349}
2350
2351//-----------------------------make_runtime_call-------------------------------
2352Node* GraphKit::make_runtime_call(int flags,
2353                                  const TypeFunc* call_type, address call_addr,
2354                                  const char* call_name,
2355                                  const TypePtr* adr_type,
2356                                  // The following parms are all optional.
2357                                  // The first NULL ends the list.
2358                                  Node* parm0, Node* parm1,
2359                                  Node* parm2, Node* parm3,
2360                                  Node* parm4, Node* parm5,
2361                                  Node* parm6, Node* parm7) {
2362  // Slow-path call
2363  bool is_leaf = !(flags & RC_NO_LEAF);
2364  bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2365  if (call_name == NULL) {
2366    assert(!is_leaf, "must supply name for leaf");
2367    call_name = OptoRuntime::stub_name(call_addr);
2368  }
2369  CallNode* call;
2370  if (!is_leaf) {
2371    call = new CallStaticJavaNode(call_type, call_addr, call_name,
2372                                           bci(), adr_type);
2373  } else if (flags & RC_NO_FP) {
2374    call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2375  } else {
2376    call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2377  }
2378
2379  // The following is similar to set_edges_for_java_call,
2380  // except that the memory effects of the call are restricted to AliasIdxRaw.
2381
2382  // Slow path call has no side-effects, uses few values
2383  bool wide_in  = !(flags & RC_NARROW_MEM);
2384  bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2385
2386  Node* prev_mem = NULL;
2387  if (wide_in) {
2388    prev_mem = set_predefined_input_for_runtime_call(call);
2389  } else {
2390    assert(!wide_out, "narrow in => narrow out");
2391    Node* narrow_mem = memory(adr_type);
2392    prev_mem = reset_memory();
2393    map()->set_memory(narrow_mem);
2394    set_predefined_input_for_runtime_call(call);
2395  }
2396
2397  // Hook each parm in order.  Stop looking at the first NULL.
2398  if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
2399  if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
2400  if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
2401  if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
2402  if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
2403  if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
2404  if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
2405  if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
2406    /* close each nested if ===> */  } } } } } } } }
2407  assert(call->in(call->req()-1) != NULL, "must initialize all parms");
2408
2409  if (!is_leaf) {
2410    // Non-leaves can block and take safepoints:
2411    add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2412  }
2413  // Non-leaves can throw exceptions:
2414  if (has_io) {
2415    call->set_req(TypeFunc::I_O, i_o());
2416  }
2417
2418  if (flags & RC_UNCOMMON) {
2419    // Set the count to a tiny probability.  Cf. Estimate_Block_Frequency.
2420    // (An "if" probability corresponds roughly to an unconditional count.
2421    // Sort of.)
2422    call->set_cnt(PROB_UNLIKELY_MAG(4));
2423  }
2424
2425  Node* c = _gvn.transform(call);
2426  assert(c == call, "cannot disappear");
2427
2428  if (wide_out) {
2429    // Slow path call has full side-effects.
2430    set_predefined_output_for_runtime_call(call);
2431  } else {
2432    // Slow path call has few side-effects, and/or sets few values.
2433    set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2434  }
2435
2436  if (has_io) {
2437    set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2438  }
2439  return call;
2440
2441}
2442
2443//------------------------------merge_memory-----------------------------------
2444// Merge memory from one path into the current memory state.
2445void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2446  for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2447    Node* old_slice = mms.force_memory();
2448    Node* new_slice = mms.memory2();
2449    if (old_slice != new_slice) {
2450      PhiNode* phi;
2451      if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2452        if (mms.is_empty()) {
2453          // clone base memory Phi's inputs for this memory slice
2454          assert(old_slice == mms.base_memory(), "sanity");
2455          phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2456          _gvn.set_type(phi, Type::MEMORY);
2457          for (uint i = 1; i < phi->req(); i++) {
2458            phi->init_req(i, old_slice->in(i));
2459          }
2460        } else {
2461          phi = old_slice->as_Phi(); // Phi was generated already
2462        }
2463      } else {
2464        phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2465        _gvn.set_type(phi, Type::MEMORY);
2466      }
2467      phi->set_req(new_path, new_slice);
2468      mms.set_memory(phi);
2469    }
2470  }
2471}
2472
2473//------------------------------make_slow_call_ex------------------------------
2474// Make the exception handler hookups for the slow call
2475void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2476  if (stopped())  return;
2477
2478  // Make a catch node with just two handlers:  fall-through and catch-all
2479  Node* i_o  = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2480  Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2481  Node* norm = _gvn.transform( new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci) );
2482  Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci) );
2483
2484  { PreserveJVMState pjvms(this);
2485    set_control(excp);
2486    set_i_o(i_o);
2487
2488    if (excp != top()) {
2489      if (deoptimize) {
2490        // Deoptimize if an exception is caught. Don't construct exception state in this case.
2491        uncommon_trap(Deoptimization::Reason_unhandled,
2492                      Deoptimization::Action_none);
2493      } else {
2494        // Create an exception state also.
2495        // Use an exact type if the caller has specified a specific exception.
2496        const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2497        Node*       ex_oop  = new CreateExNode(ex_type, control(), i_o);
2498        add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2499      }
2500    }
2501  }
2502
2503  // Get the no-exception control from the CatchNode.
2504  set_control(norm);
2505}
2506
2507static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN* gvn, BasicType bt) {
2508  Node* cmp = NULL;
2509  switch(bt) {
2510  case T_INT: cmp = new CmpINode(in1, in2); break;
2511  case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2512  default: fatal(err_msg("unexpected comparison type %s", type2name(bt)));
2513  }
2514  gvn->transform(cmp);
2515  Node* bol = gvn->transform(new BoolNode(cmp, test));
2516  IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2517  gvn->transform(iff);
2518  if (!bol->is_Con()) gvn->record_for_igvn(iff);
2519  return iff;
2520}
2521
2522
2523//-------------------------------gen_subtype_check-----------------------------
2524// Generate a subtyping check.  Takes as input the subtype and supertype.
2525// Returns 2 values: sets the default control() to the true path and returns
2526// the false path.  Only reads invariant memory; sets no (visible) memory.
2527// The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2528// but that's not exposed to the optimizer.  This call also doesn't take in an
2529// Object; if you wish to check an Object you need to load the Object's class
2530// prior to coming here.
2531Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, MergeMemNode* mem, PhaseGVN* gvn) {
2532  Compile* C = gvn->C;
2533
2534  if ((*ctrl)->is_top()) {
2535    return C->top();
2536  }
2537
2538  // Fast check for identical types, perhaps identical constants.
2539  // The types can even be identical non-constants, in cases
2540  // involving Array.newInstance, Object.clone, etc.
2541  if (subklass == superklass)
2542    return C->top();             // false path is dead; no test needed.
2543
2544  if (gvn->type(superklass)->singleton()) {
2545    ciKlass* superk = gvn->type(superklass)->is_klassptr()->klass();
2546    ciKlass* subk   = gvn->type(subklass)->is_klassptr()->klass();
2547
2548    // In the common case of an exact superklass, try to fold up the
2549    // test before generating code.  You may ask, why not just generate
2550    // the code and then let it fold up?  The answer is that the generated
2551    // code will necessarily include null checks, which do not always
2552    // completely fold away.  If they are also needless, then they turn
2553    // into a performance loss.  Example:
2554    //    Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2555    // Here, the type of 'fa' is often exact, so the store check
2556    // of fa[1]=x will fold up, without testing the nullness of x.
2557    switch (C->static_subtype_check(superk, subk)) {
2558    case Compile::SSC_always_false:
2559      {
2560        Node* always_fail = *ctrl;
2561        *ctrl = gvn->C->top();
2562        return always_fail;
2563      }
2564    case Compile::SSC_always_true:
2565      return C->top();
2566    case Compile::SSC_easy_test:
2567      {
2568        // Just do a direct pointer compare and be done.
2569        IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2570        *ctrl = gvn->transform(new IfTrueNode(iff));
2571        return gvn->transform(new IfFalseNode(iff));
2572      }
2573    case Compile::SSC_full_test:
2574      break;
2575    default:
2576      ShouldNotReachHere();
2577    }
2578  }
2579
2580  // %%% Possible further optimization:  Even if the superklass is not exact,
2581  // if the subklass is the unique subtype of the superklass, the check
2582  // will always succeed.  We could leave a dependency behind to ensure this.
2583
2584  // First load the super-klass's check-offset
2585  Node *p1 = gvn->transform(new AddPNode(superklass, superklass, gvn->MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2586  Node* m = mem->memory_at(C->get_alias_index(gvn->type(p1)->is_ptr()));
2587  Node *chk_off = gvn->transform(new LoadINode(NULL, m, p1, gvn->type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2588  int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2589  bool might_be_cache = (gvn->find_int_con(chk_off, cacheoff_con) == cacheoff_con);
2590
2591  // Load from the sub-klass's super-class display list, or a 1-word cache of
2592  // the secondary superclass list, or a failing value with a sentinel offset
2593  // if the super-klass is an interface or exceptionally deep in the Java
2594  // hierarchy and we have to scan the secondary superclass list the hard way.
2595  // Worst-case type is a little odd: NULL is allowed as a result (usually
2596  // klass loads can never produce a NULL).
2597  Node *chk_off_X = chk_off;
2598#ifdef _LP64
2599  chk_off_X = gvn->transform(new ConvI2LNode(chk_off_X));
2600#endif
2601  Node *p2 = gvn->transform(new AddPNode(subklass,subklass,chk_off_X));
2602  // For some types like interfaces the following loadKlass is from a 1-word
2603  // cache which is mutable so can't use immutable memory.  Other
2604  // types load from the super-class display table which is immutable.
2605  m = mem->memory_at(C->get_alias_index(gvn->type(p2)->is_ptr()));
2606  Node *kmem = might_be_cache ? m : C->immutable_memory();
2607  Node *nkls = gvn->transform(LoadKlassNode::make(*gvn, NULL, kmem, p2, gvn->type(p2)->is_ptr(), TypeKlassPtr::OBJECT_OR_NULL));
2608
2609  // Compile speed common case: ARE a subtype and we canNOT fail
2610  if( superklass == nkls )
2611    return C->top();             // false path is dead; no test needed.
2612
2613  // See if we get an immediate positive hit.  Happens roughly 83% of the
2614  // time.  Test to see if the value loaded just previously from the subklass
2615  // is exactly the superklass.
2616  IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2617  Node *iftrue1 = gvn->transform( new IfTrueNode (iff1));
2618  *ctrl = gvn->transform(new IfFalseNode(iff1));
2619
2620  // Compile speed common case: Check for being deterministic right now.  If
2621  // chk_off is a constant and not equal to cacheoff then we are NOT a
2622  // subklass.  In this case we need exactly the 1 test above and we can
2623  // return those results immediately.
2624  if (!might_be_cache) {
2625    Node* not_subtype_ctrl = *ctrl;
2626    *ctrl = iftrue1; // We need exactly the 1 test above
2627    return not_subtype_ctrl;
2628  }
2629
2630  // Gather the various success & failures here
2631  RegionNode *r_ok_subtype = new RegionNode(4);
2632  gvn->record_for_igvn(r_ok_subtype);
2633  RegionNode *r_not_subtype = new RegionNode(3);
2634  gvn->record_for_igvn(r_not_subtype);
2635
2636  r_ok_subtype->init_req(1, iftrue1);
2637
2638  // Check for immediate negative hit.  Happens roughly 11% of the time (which
2639  // is roughly 63% of the remaining cases).  Test to see if the loaded
2640  // check-offset points into the subklass display list or the 1-element
2641  // cache.  If it points to the display (and NOT the cache) and the display
2642  // missed then it's not a subtype.
2643  Node *cacheoff = gvn->intcon(cacheoff_con);
2644  IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2645  r_not_subtype->init_req(1, gvn->transform(new IfTrueNode (iff2)));
2646  *ctrl = gvn->transform(new IfFalseNode(iff2));
2647
2648  // Check for self.  Very rare to get here, but it is taken 1/3 the time.
2649  // No performance impact (too rare) but allows sharing of secondary arrays
2650  // which has some footprint reduction.
2651  IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2652  r_ok_subtype->init_req(2, gvn->transform(new IfTrueNode(iff3)));
2653  *ctrl = gvn->transform(new IfFalseNode(iff3));
2654
2655  // -- Roads not taken here: --
2656  // We could also have chosen to perform the self-check at the beginning
2657  // of this code sequence, as the assembler does.  This would not pay off
2658  // the same way, since the optimizer, unlike the assembler, can perform
2659  // static type analysis to fold away many successful self-checks.
2660  // Non-foldable self checks work better here in second position, because
2661  // the initial primary superclass check subsumes a self-check for most
2662  // types.  An exception would be a secondary type like array-of-interface,
2663  // which does not appear in its own primary supertype display.
2664  // Finally, we could have chosen to move the self-check into the
2665  // PartialSubtypeCheckNode, and from there out-of-line in a platform
2666  // dependent manner.  But it is worthwhile to have the check here,
2667  // where it can be perhaps be optimized.  The cost in code space is
2668  // small (register compare, branch).
2669
2670  // Now do a linear scan of the secondary super-klass array.  Again, no real
2671  // performance impact (too rare) but it's gotta be done.
2672  // Since the code is rarely used, there is no penalty for moving it
2673  // out of line, and it can only improve I-cache density.
2674  // The decision to inline or out-of-line this final check is platform
2675  // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2676  Node* psc = gvn->transform(
2677    new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2678
2679  IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn->zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2680  r_not_subtype->init_req(2, gvn->transform(new IfTrueNode (iff4)));
2681  r_ok_subtype ->init_req(3, gvn->transform(new IfFalseNode(iff4)));
2682
2683  // Return false path; set default control to true path.
2684  *ctrl = gvn->transform(r_ok_subtype);
2685  return gvn->transform(r_not_subtype);
2686}
2687
2688// Profile-driven exact type check:
2689Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2690                                    float prob,
2691                                    Node* *casted_receiver) {
2692  const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2693  Node* recv_klass = load_object_klass(receiver);
2694  Node* want_klass = makecon(tklass);
2695  Node* cmp = _gvn.transform( new CmpPNode(recv_klass, want_klass) );
2696  Node* bol = _gvn.transform( new BoolNode(cmp, BoolTest::eq) );
2697  IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2698  set_control( _gvn.transform( new IfTrueNode (iff) ));
2699  Node* fail = _gvn.transform( new IfFalseNode(iff) );
2700
2701  const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2702  assert(recv_xtype->klass_is_exact(), "");
2703
2704  // Subsume downstream occurrences of receiver with a cast to
2705  // recv_xtype, since now we know what the type will be.
2706  Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2707  (*casted_receiver) = _gvn.transform(cast);
2708  // (User must make the replace_in_map call.)
2709
2710  return fail;
2711}
2712
2713
2714//------------------------------seems_never_null-------------------------------
2715// Use null_seen information if it is available from the profile.
2716// If we see an unexpected null at a type check we record it and force a
2717// recompile; the offending check will be recompiled to handle NULLs.
2718// If we see several offending BCIs, then all checks in the
2719// method will be recompiled.
2720bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2721  speculating = !_gvn.type(obj)->speculative_maybe_null();
2722  Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2723  if (UncommonNullCast               // Cutout for this technique
2724      && obj != null()               // And not the -Xcomp stupid case?
2725      && !too_many_traps(reason)
2726      ) {
2727    if (speculating) {
2728      return true;
2729    }
2730    if (data == NULL)
2731      // Edge case:  no mature data.  Be optimistic here.
2732      return true;
2733    // If the profile has not seen a null, assume it won't happen.
2734    assert(java_bc() == Bytecodes::_checkcast ||
2735           java_bc() == Bytecodes::_instanceof ||
2736           java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
2737    return !data->as_BitData()->null_seen();
2738  }
2739  speculating = false;
2740  return false;
2741}
2742
2743//------------------------maybe_cast_profiled_receiver-------------------------
2744// If the profile has seen exactly one type, narrow to exactly that type.
2745// Subsequent type checks will always fold up.
2746Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
2747                                             ciKlass* require_klass,
2748                                             ciKlass* spec_klass,
2749                                             bool safe_for_replace) {
2750  if (!UseTypeProfile || !TypeProfileCasts) return NULL;
2751
2752  Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
2753
2754  // Make sure we haven't already deoptimized from this tactic.
2755  if (too_many_traps(reason) || too_many_recompiles(reason))
2756    return NULL;
2757
2758  // (No, this isn't a call, but it's enough like a virtual call
2759  // to use the same ciMethod accessor to get the profile info...)
2760  // If we have a speculative type use it instead of profiling (which
2761  // may not help us)
2762  ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;
2763  if (exact_kls != NULL) {// no cast failures here
2764    if (require_klass == NULL ||
2765        C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
2766      // If we narrow the type to match what the type profile sees or
2767      // the speculative type, we can then remove the rest of the
2768      // cast.
2769      // This is a win, even if the exact_kls is very specific,
2770      // because downstream operations, such as method calls,
2771      // will often benefit from the sharper type.
2772      Node* exact_obj = not_null_obj; // will get updated in place...
2773      Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
2774                                            &exact_obj);
2775      { PreserveJVMState pjvms(this);
2776        set_control(slow_ctl);
2777        uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
2778      }
2779      if (safe_for_replace) {
2780        replace_in_map(not_null_obj, exact_obj);
2781      }
2782      return exact_obj;
2783    }
2784    // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
2785  }
2786
2787  return NULL;
2788}
2789
2790/**
2791 * Cast obj to type and emit guard unless we had too many traps here
2792 * already
2793 *
2794 * @param obj       node being casted
2795 * @param type      type to cast the node to
2796 * @param not_null  true if we know node cannot be null
2797 */
2798Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
2799                                        ciKlass* type,
2800                                        bool not_null) {
2801  if (stopped()) {
2802    return obj;
2803  }
2804
2805  // type == NULL if profiling tells us this object is always null
2806  if (type != NULL) {
2807    Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
2808    Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
2809
2810    if (!too_many_traps(null_reason) && !too_many_recompiles(null_reason) &&
2811        !too_many_traps(class_reason) &&
2812        !too_many_recompiles(class_reason)) {
2813      Node* not_null_obj = NULL;
2814      // not_null is true if we know the object is not null and
2815      // there's no need for a null check
2816      if (!not_null) {
2817        Node* null_ctl = top();
2818        not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
2819        assert(null_ctl->is_top(), "no null control here");
2820      } else {
2821        not_null_obj = obj;
2822      }
2823
2824      Node* exact_obj = not_null_obj;
2825      ciKlass* exact_kls = type;
2826      Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
2827                                            &exact_obj);
2828      {
2829        PreserveJVMState pjvms(this);
2830        set_control(slow_ctl);
2831        uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
2832      }
2833      replace_in_map(not_null_obj, exact_obj);
2834      obj = exact_obj;
2835    }
2836  } else {
2837    if (!too_many_traps(Deoptimization::Reason_null_assert) &&
2838        !too_many_recompiles(Deoptimization::Reason_null_assert)) {
2839      Node* exact_obj = null_assert(obj);
2840      replace_in_map(obj, exact_obj);
2841      obj = exact_obj;
2842    }
2843  }
2844  return obj;
2845}
2846
2847//-------------------------------gen_instanceof--------------------------------
2848// Generate an instance-of idiom.  Used by both the instance-of bytecode
2849// and the reflective instance-of call.
2850Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
2851  kill_dead_locals();           // Benefit all the uncommon traps
2852  assert( !stopped(), "dead parse path should be checked in callers" );
2853  assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
2854         "must check for not-null not-dead klass in callers");
2855
2856  // Make the merge point
2857  enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
2858  RegionNode* region = new RegionNode(PATH_LIMIT);
2859  Node*       phi    = new PhiNode(region, TypeInt::BOOL);
2860  C->set_has_split_ifs(true); // Has chance for split-if optimization
2861
2862  ciProfileData* data = NULL;
2863  if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
2864    data = method()->method_data()->bci_to_data(bci());
2865  }
2866  bool speculative_not_null = false;
2867  bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
2868                         && seems_never_null(obj, data, speculative_not_null));
2869
2870  // Null check; get casted pointer; set region slot 3
2871  Node* null_ctl = top();
2872  Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
2873
2874  // If not_null_obj is dead, only null-path is taken
2875  if (stopped()) {              // Doing instance-of on a NULL?
2876    set_control(null_ctl);
2877    return intcon(0);
2878  }
2879  region->init_req(_null_path, null_ctl);
2880  phi   ->init_req(_null_path, intcon(0)); // Set null path value
2881  if (null_ctl == top()) {
2882    // Do this eagerly, so that pattern matches like is_diamond_phi
2883    // will work even during parsing.
2884    assert(_null_path == PATH_LIMIT-1, "delete last");
2885    region->del_req(_null_path);
2886    phi   ->del_req(_null_path);
2887  }
2888
2889  // Do we know the type check always succeed?
2890  bool known_statically = false;
2891  if (_gvn.type(superklass)->singleton()) {
2892    ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
2893    ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
2894    if (subk != NULL && subk->is_loaded()) {
2895      int static_res = C->static_subtype_check(superk, subk);
2896      known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
2897    }
2898  }
2899
2900  if (known_statically && UseTypeSpeculation) {
2901    // If we know the type check always succeeds then we don't use the
2902    // profiling data at this bytecode. Don't lose it, feed it to the
2903    // type system as a speculative type.
2904    not_null_obj = record_profiled_receiver_for_speculation(not_null_obj);
2905  } else {
2906    const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
2907    // We may not have profiling here or it may not help us. If we
2908    // have a speculative type use it to perform an exact cast.
2909    ciKlass* spec_obj_type = obj_type->speculative_type();
2910    if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
2911      Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
2912      if (stopped()) {            // Profile disagrees with this path.
2913        set_control(null_ctl);    // Null is the only remaining possibility.
2914        return intcon(0);
2915      }
2916      if (cast_obj != NULL) {
2917        not_null_obj = cast_obj;
2918      }
2919    }
2920  }
2921
2922  // Load the object's klass
2923  Node* obj_klass = load_object_klass(not_null_obj);
2924
2925  // Generate the subtype check
2926  Node* not_subtype_ctrl = gen_subtype_check(obj_klass, superklass);
2927
2928  // Plug in the success path to the general merge in slot 1.
2929  region->init_req(_obj_path, control());
2930  phi   ->init_req(_obj_path, intcon(1));
2931
2932  // Plug in the failing path to the general merge in slot 2.
2933  region->init_req(_fail_path, not_subtype_ctrl);
2934  phi   ->init_req(_fail_path, intcon(0));
2935
2936  // Return final merged results
2937  set_control( _gvn.transform(region) );
2938  record_for_igvn(region);
2939  return _gvn.transform(phi);
2940}
2941
2942//-------------------------------gen_checkcast---------------------------------
2943// Generate a checkcast idiom.  Used by both the checkcast bytecode and the
2944// array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
2945// uncommon-trap paths work.  Adjust stack after this call.
2946// If failure_control is supplied and not null, it is filled in with
2947// the control edge for the cast failure.  Otherwise, an appropriate
2948// uncommon trap or exception is thrown.
2949Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
2950                              Node* *failure_control) {
2951  kill_dead_locals();           // Benefit all the uncommon traps
2952  const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
2953  const Type *toop = TypeOopPtr::make_from_klass(tk->klass());
2954
2955  // Fast cutout:  Check the case that the cast is vacuously true.
2956  // This detects the common cases where the test will short-circuit
2957  // away completely.  We do this before we perform the null check,
2958  // because if the test is going to turn into zero code, we don't
2959  // want a residual null check left around.  (Causes a slowdown,
2960  // for example, in some objArray manipulations, such as a[i]=a[j].)
2961  if (tk->singleton()) {
2962    const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
2963    if (objtp != NULL && objtp->klass() != NULL) {
2964      switch (C->static_subtype_check(tk->klass(), objtp->klass())) {
2965      case Compile::SSC_always_true:
2966        // If we know the type check always succeed then we don't use
2967        // the profiling data at this bytecode. Don't lose it, feed it
2968        // to the type system as a speculative type.
2969        return record_profiled_receiver_for_speculation(obj);
2970      case Compile::SSC_always_false:
2971        // It needs a null check because a null will *pass* the cast check.
2972        // A non-null value will always produce an exception.
2973        return null_assert(obj);
2974      }
2975    }
2976  }
2977
2978  ciProfileData* data = NULL;
2979  bool safe_for_replace = false;
2980  if (failure_control == NULL) {        // use MDO in regular case only
2981    assert(java_bc() == Bytecodes::_aastore ||
2982           java_bc() == Bytecodes::_checkcast,
2983           "interpreter profiles type checks only for these BCs");
2984    data = method()->method_data()->bci_to_data(bci());
2985    safe_for_replace = true;
2986  }
2987
2988  // Make the merge point
2989  enum { _obj_path = 1, _null_path, PATH_LIMIT };
2990  RegionNode* region = new RegionNode(PATH_LIMIT);
2991  Node*       phi    = new PhiNode(region, toop);
2992  C->set_has_split_ifs(true); // Has chance for split-if optimization
2993
2994  // Use null-cast information if it is available
2995  bool speculative_not_null = false;
2996  bool never_see_null = ((failure_control == NULL)  // regular case only
2997                         && seems_never_null(obj, data, speculative_not_null));
2998
2999  // Null check; get casted pointer; set region slot 3
3000  Node* null_ctl = top();
3001  Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3002
3003  // If not_null_obj is dead, only null-path is taken
3004  if (stopped()) {              // Doing instance-of on a NULL?
3005    set_control(null_ctl);
3006    return null();
3007  }
3008  region->init_req(_null_path, null_ctl);
3009  phi   ->init_req(_null_path, null());  // Set null path value
3010  if (null_ctl == top()) {
3011    // Do this eagerly, so that pattern matches like is_diamond_phi
3012    // will work even during parsing.
3013    assert(_null_path == PATH_LIMIT-1, "delete last");
3014    region->del_req(_null_path);
3015    phi   ->del_req(_null_path);
3016  }
3017
3018  Node* cast_obj = NULL;
3019  if (tk->klass_is_exact()) {
3020    // The following optimization tries to statically cast the speculative type of the object
3021    // (for example obtained during profiling) to the type of the superklass and then do a
3022    // dynamic check that the type of the object is what we expect. To work correctly
3023    // for checkcast and aastore the type of superklass should be exact.
3024    const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3025    // We may not have profiling here or it may not help us. If we have
3026    // a speculative type use it to perform an exact cast.
3027    ciKlass* spec_obj_type = obj_type->speculative_type();
3028    if (spec_obj_type != NULL || data != NULL) {
3029      cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
3030      if (cast_obj != NULL) {
3031        if (failure_control != NULL) // failure is now impossible
3032          (*failure_control) = top();
3033        // adjust the type of the phi to the exact klass:
3034        phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3035      }
3036    }
3037  }
3038
3039  if (cast_obj == NULL) {
3040    // Load the object's klass
3041    Node* obj_klass = load_object_klass(not_null_obj);
3042
3043    // Generate the subtype check
3044    Node* not_subtype_ctrl = gen_subtype_check( obj_klass, superklass );
3045
3046    // Plug in success path into the merge
3047    cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3048    // Failure path ends in uncommon trap (or may be dead - failure impossible)
3049    if (failure_control == NULL) {
3050      if (not_subtype_ctrl != top()) { // If failure is possible
3051        PreserveJVMState pjvms(this);
3052        set_control(not_subtype_ctrl);
3053        builtin_throw(Deoptimization::Reason_class_check, obj_klass);
3054      }
3055    } else {
3056      (*failure_control) = not_subtype_ctrl;
3057    }
3058  }
3059
3060  region->init_req(_obj_path, control());
3061  phi   ->init_req(_obj_path, cast_obj);
3062
3063  // A merge of NULL or Casted-NotNull obj
3064  Node* res = _gvn.transform(phi);
3065
3066  // Note I do NOT always 'replace_in_map(obj,result)' here.
3067  //  if( tk->klass()->can_be_primary_super()  )
3068    // This means that if I successfully store an Object into an array-of-String
3069    // I 'forget' that the Object is really now known to be a String.  I have to
3070    // do this because we don't have true union types for interfaces - if I store
3071    // a Baz into an array-of-Interface and then tell the optimizer it's an
3072    // Interface, I forget that it's also a Baz and cannot do Baz-like field
3073    // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3074  //  replace_in_map( obj, res );
3075
3076  // Return final merged results
3077  set_control( _gvn.transform(region) );
3078  record_for_igvn(region);
3079  return res;
3080}
3081
3082//------------------------------next_monitor-----------------------------------
3083// What number should be given to the next monitor?
3084int GraphKit::next_monitor() {
3085  int current = jvms()->monitor_depth()* C->sync_stack_slots();
3086  int next = current + C->sync_stack_slots();
3087  // Keep the toplevel high water mark current:
3088  if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3089  return current;
3090}
3091
3092//------------------------------insert_mem_bar---------------------------------
3093// Memory barrier to avoid floating things around
3094// The membar serves as a pinch point between both control and all memory slices.
3095Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3096  MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3097  mb->init_req(TypeFunc::Control, control());
3098  mb->init_req(TypeFunc::Memory,  reset_memory());
3099  Node* membar = _gvn.transform(mb);
3100  set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3101  set_all_memory_call(membar);
3102  return membar;
3103}
3104
3105//-------------------------insert_mem_bar_volatile----------------------------
3106// Memory barrier to avoid floating things around
3107// The membar serves as a pinch point between both control and memory(alias_idx).
3108// If you want to make a pinch point on all memory slices, do not use this
3109// function (even with AliasIdxBot); use insert_mem_bar() instead.
3110Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3111  // When Parse::do_put_xxx updates a volatile field, it appends a series
3112  // of MemBarVolatile nodes, one for *each* volatile field alias category.
3113  // The first membar is on the same memory slice as the field store opcode.
3114  // This forces the membar to follow the store.  (Bug 6500685 broke this.)
3115  // All the other membars (for other volatile slices, including AliasIdxBot,
3116  // which stands for all unknown volatile slices) are control-dependent
3117  // on the first membar.  This prevents later volatile loads or stores
3118  // from sliding up past the just-emitted store.
3119
3120  MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
3121  mb->set_req(TypeFunc::Control,control());
3122  if (alias_idx == Compile::AliasIdxBot) {
3123    mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
3124  } else {
3125    assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
3126    mb->set_req(TypeFunc::Memory, memory(alias_idx));
3127  }
3128  Node* membar = _gvn.transform(mb);
3129  set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3130  if (alias_idx == Compile::AliasIdxBot) {
3131    merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3132  } else {
3133    set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3134  }
3135  return membar;
3136}
3137
3138//------------------------------shared_lock------------------------------------
3139// Emit locking code.
3140FastLockNode* GraphKit::shared_lock(Node* obj) {
3141  // bci is either a monitorenter bc or InvocationEntryBci
3142  // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3143  assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3144
3145  if( !GenerateSynchronizationCode )
3146    return NULL;                // Not locking things?
3147  if (stopped())                // Dead monitor?
3148    return NULL;
3149
3150  assert(dead_locals_are_killed(), "should kill locals before sync. point");
3151
3152  // Box the stack location
3153  Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3154  Node* mem = reset_memory();
3155
3156  FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3157  if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {
3158    // Create the counters for this fast lock.
3159    flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3160  }
3161
3162  // Create the rtm counters for this fast lock if needed.
3163  flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3164
3165  // Add monitor to debug info for the slow path.  If we block inside the
3166  // slow path and de-opt, we need the monitor hanging around
3167  map()->push_monitor( flock );
3168
3169  const TypeFunc *tf = LockNode::lock_type();
3170  LockNode *lock = new LockNode(C, tf);
3171
3172  lock->init_req( TypeFunc::Control, control() );
3173  lock->init_req( TypeFunc::Memory , mem );
3174  lock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3175  lock->init_req( TypeFunc::FramePtr, frameptr() );
3176  lock->init_req( TypeFunc::ReturnAdr, top() );
3177
3178  lock->init_req(TypeFunc::Parms + 0, obj);
3179  lock->init_req(TypeFunc::Parms + 1, box);
3180  lock->init_req(TypeFunc::Parms + 2, flock);
3181  add_safepoint_edges(lock);
3182
3183  lock = _gvn.transform( lock )->as_Lock();
3184
3185  // lock has no side-effects, sets few values
3186  set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
3187
3188  insert_mem_bar(Op_MemBarAcquireLock);
3189
3190  // Add this to the worklist so that the lock can be eliminated
3191  record_for_igvn(lock);
3192
3193#ifndef PRODUCT
3194  if (PrintLockStatistics) {
3195    // Update the counter for this lock.  Don't bother using an atomic
3196    // operation since we don't require absolute accuracy.
3197    lock->create_lock_counter(map()->jvms());
3198    increment_counter(lock->counter()->addr());
3199  }
3200#endif
3201
3202  return flock;
3203}
3204
3205
3206//------------------------------shared_unlock----------------------------------
3207// Emit unlocking code.
3208void GraphKit::shared_unlock(Node* box, Node* obj) {
3209  // bci is either a monitorenter bc or InvocationEntryBci
3210  // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3211  assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3212
3213  if( !GenerateSynchronizationCode )
3214    return;
3215  if (stopped()) {               // Dead monitor?
3216    map()->pop_monitor();        // Kill monitor from debug info
3217    return;
3218  }
3219
3220  // Memory barrier to avoid floating things down past the locked region
3221  insert_mem_bar(Op_MemBarReleaseLock);
3222
3223  const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3224  UnlockNode *unlock = new UnlockNode(C, tf);
3225#ifdef ASSERT
3226  unlock->set_dbg_jvms(sync_jvms());
3227#endif
3228  uint raw_idx = Compile::AliasIdxRaw;
3229  unlock->init_req( TypeFunc::Control, control() );
3230  unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3231  unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3232  unlock->init_req( TypeFunc::FramePtr, frameptr() );
3233  unlock->init_req( TypeFunc::ReturnAdr, top() );
3234
3235  unlock->init_req(TypeFunc::Parms + 0, obj);
3236  unlock->init_req(TypeFunc::Parms + 1, box);
3237  unlock = _gvn.transform(unlock)->as_Unlock();
3238
3239  Node* mem = reset_memory();
3240
3241  // unlock has no side-effects, sets few values
3242  set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3243
3244  // Kill monitor from debug info
3245  map()->pop_monitor( );
3246}
3247
3248//-------------------------------get_layout_helper-----------------------------
3249// If the given klass is a constant or known to be an array,
3250// fetch the constant layout helper value into constant_value
3251// and return (Node*)NULL.  Otherwise, load the non-constant
3252// layout helper value, and return the node which represents it.
3253// This two-faced routine is useful because allocation sites
3254// almost always feature constant types.
3255Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3256  const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3257  if (!StressReflectiveCode && inst_klass != NULL) {
3258    ciKlass* klass = inst_klass->klass();
3259    bool    xklass = inst_klass->klass_is_exact();
3260    if (xklass || klass->is_array_klass()) {
3261      jint lhelper = klass->layout_helper();
3262      if (lhelper != Klass::_lh_neutral_value) {
3263        constant_value = lhelper;
3264        return (Node*) NULL;
3265      }
3266    }
3267  }
3268  constant_value = Klass::_lh_neutral_value;  // put in a known value
3269  Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3270  return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3271}
3272
3273// We just put in an allocate/initialize with a big raw-memory effect.
3274// Hook selected additional alias categories on the initialization.
3275static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3276                                MergeMemNode* init_in_merge,
3277                                Node* init_out_raw) {
3278  DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3279  assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3280
3281  Node* prevmem = kit.memory(alias_idx);
3282  init_in_merge->set_memory_at(alias_idx, prevmem);
3283  kit.set_memory(init_out_raw, alias_idx);
3284}
3285
3286//---------------------------set_output_for_allocation-------------------------
3287Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3288                                          const TypeOopPtr* oop_type,
3289                                          bool deoptimize_on_exception) {
3290  int rawidx = Compile::AliasIdxRaw;
3291  alloc->set_req( TypeFunc::FramePtr, frameptr() );
3292  add_safepoint_edges(alloc);
3293  Node* allocx = _gvn.transform(alloc);
3294  set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3295  // create memory projection for i_o
3296  set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3297  make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3298
3299  // create a memory projection as for the normal control path
3300  Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3301  set_memory(malloc, rawidx);
3302
3303  // a normal slow-call doesn't change i_o, but an allocation does
3304  // we create a separate i_o projection for the normal control path
3305  set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3306  Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3307
3308  // put in an initialization barrier
3309  InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3310                                                 rawoop)->as_Initialize();
3311  assert(alloc->initialization() == init,  "2-way macro link must work");
3312  assert(init ->allocation()     == alloc, "2-way macro link must work");
3313  {
3314    // Extract memory strands which may participate in the new object's
3315    // initialization, and source them from the new InitializeNode.
3316    // This will allow us to observe initializations when they occur,
3317    // and link them properly (as a group) to the InitializeNode.
3318    assert(init->in(InitializeNode::Memory) == malloc, "");
3319    MergeMemNode* minit_in = MergeMemNode::make(malloc);
3320    init->set_req(InitializeNode::Memory, minit_in);
3321    record_for_igvn(minit_in); // fold it up later, if possible
3322    Node* minit_out = memory(rawidx);
3323    assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3324    if (oop_type->isa_aryptr()) {
3325      const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3326      int            elemidx  = C->get_alias_index(telemref);
3327      hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3328    } else if (oop_type->isa_instptr()) {
3329      ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3330      for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3331        ciField* field = ik->nonstatic_field_at(i);
3332        if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3333          continue;  // do not bother to track really large numbers of fields
3334        // Find (or create) the alias category for this field:
3335        int fieldidx = C->alias_type(field)->index();
3336        hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3337      }
3338    }
3339  }
3340
3341  // Cast raw oop to the real thing...
3342  Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3343  javaoop = _gvn.transform(javaoop);
3344  C->set_recent_alloc(control(), javaoop);
3345  assert(just_allocated_object(control()) == javaoop, "just allocated");
3346
3347#ifdef ASSERT
3348  { // Verify that the AllocateNode::Ideal_allocation recognizers work:
3349    assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,
3350           "Ideal_allocation works");
3351    assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,
3352           "Ideal_allocation works");
3353    if (alloc->is_AllocateArray()) {
3354      assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),
3355             "Ideal_allocation works");
3356      assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),
3357             "Ideal_allocation works");
3358    } else {
3359      assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3360    }
3361  }
3362#endif //ASSERT
3363
3364  return javaoop;
3365}
3366
3367//---------------------------new_instance--------------------------------------
3368// This routine takes a klass_node which may be constant (for a static type)
3369// or may be non-constant (for reflective code).  It will work equally well
3370// for either, and the graph will fold nicely if the optimizer later reduces
3371// the type to a constant.
3372// The optional arguments are for specialized use by intrinsics:
3373//  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3374//  - If 'return_size_val', report the the total object size to the caller.
3375//  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3376Node* GraphKit::new_instance(Node* klass_node,
3377                             Node* extra_slow_test,
3378                             Node* *return_size_val,
3379                             bool deoptimize_on_exception) {
3380  // Compute size in doublewords
3381  // The size is always an integral number of doublewords, represented
3382  // as a positive bytewise size stored in the klass's layout_helper.
3383  // The layout_helper also encodes (in a low bit) the need for a slow path.
3384  jint  layout_con = Klass::_lh_neutral_value;
3385  Node* layout_val = get_layout_helper(klass_node, layout_con);
3386  int   layout_is_con = (layout_val == NULL);
3387
3388  if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3389  // Generate the initial go-slow test.  It's either ALWAYS (return a
3390  // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3391  // case) a computed value derived from the layout_helper.
3392  Node* initial_slow_test = NULL;
3393  if (layout_is_con) {
3394    assert(!StressReflectiveCode, "stress mode does not use these paths");
3395    bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3396    initial_slow_test = must_go_slow? intcon(1): extra_slow_test;
3397
3398  } else {   // reflective case
3399    // This reflective path is used by Unsafe.allocateInstance.
3400    // (It may be stress-tested by specifying StressReflectiveCode.)
3401    // Basically, we want to get into the VM is there's an illegal argument.
3402    Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3403    initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3404    if (extra_slow_test != intcon(0)) {
3405      initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3406    }
3407    // (Macro-expander will further convert this to a Bool, if necessary.)
3408  }
3409
3410  // Find the size in bytes.  This is easy; it's the layout_helper.
3411  // The size value must be valid even if the slow path is taken.
3412  Node* size = NULL;
3413  if (layout_is_con) {
3414    size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
3415  } else {   // reflective case
3416    // This reflective path is used by clone and Unsafe.allocateInstance.
3417    size = ConvI2X(layout_val);
3418
3419    // Clear the low bits to extract layout_helper_size_in_bytes:
3420    assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3421    Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3422    size = _gvn.transform( new AndXNode(size, mask) );
3423  }
3424  if (return_size_val != NULL) {
3425    (*return_size_val) = size;
3426  }
3427
3428  // This is a precise notnull oop of the klass.
3429  // (Actually, it need not be precise if this is a reflective allocation.)
3430  // It's what we cast the result to.
3431  const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3432  if (!tklass)  tklass = TypeKlassPtr::OBJECT;
3433  const TypeOopPtr* oop_type = tklass->as_instance_type();
3434
3435  // Now generate allocation code
3436
3437  // The entire memory state is needed for slow path of the allocation
3438  // since GC and deoptimization can happened.
3439  Node *mem = reset_memory();
3440  set_all_memory(mem); // Create new memory state
3441
3442  AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3443                                         control(), mem, i_o(),
3444                                         size, klass_node,
3445                                         initial_slow_test);
3446
3447  return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3448}
3449
3450//-------------------------------new_array-------------------------------------
3451// helper for both newarray and anewarray
3452// The 'length' parameter is (obviously) the length of the array.
3453// See comments on new_instance for the meaning of the other arguments.
3454Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
3455                          Node* length,         // number of array elements
3456                          int   nargs,          // number of arguments to push back for uncommon trap
3457                          Node* *return_size_val,
3458                          bool deoptimize_on_exception) {
3459  jint  layout_con = Klass::_lh_neutral_value;
3460  Node* layout_val = get_layout_helper(klass_node, layout_con);
3461  int   layout_is_con = (layout_val == NULL);
3462
3463  if (!layout_is_con && !StressReflectiveCode &&
3464      !too_many_traps(Deoptimization::Reason_class_check)) {
3465    // This is a reflective array creation site.
3466    // Optimistically assume that it is a subtype of Object[],
3467    // so that we can fold up all the address arithmetic.
3468    layout_con = Klass::array_layout_helper(T_OBJECT);
3469    Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3470    Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3471    { BuildCutout unless(this, bol_lh, PROB_MAX);
3472      inc_sp(nargs);
3473      uncommon_trap(Deoptimization::Reason_class_check,
3474                    Deoptimization::Action_maybe_recompile);
3475    }
3476    layout_val = NULL;
3477    layout_is_con = true;
3478  }
3479
3480  // Generate the initial go-slow test.  Make sure we do not overflow
3481  // if length is huge (near 2Gig) or negative!  We do not need
3482  // exact double-words here, just a close approximation of needed
3483  // double-words.  We can't add any offset or rounding bits, lest we
3484  // take a size -1 of bytes and make it positive.  Use an unsigned
3485  // compare, so negative sizes look hugely positive.
3486  int fast_size_limit = FastAllocateSizeLimit;
3487  if (layout_is_con) {
3488    assert(!StressReflectiveCode, "stress mode does not use these paths");
3489    // Increase the size limit if we have exact knowledge of array type.
3490    int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3491    fast_size_limit <<= (LogBytesPerLong - log2_esize);
3492  }
3493
3494  Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3495  Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3496  if (initial_slow_test->is_Bool()) {
3497    // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3498    initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3499  }
3500
3501  // --- Size Computation ---
3502  // array_size = round_to_heap(array_header + (length << elem_shift));
3503  // where round_to_heap(x) == round_to(x, MinObjAlignmentInBytes)
3504  // and round_to(x, y) == ((x + y-1) & ~(y-1))
3505  // The rounding mask is strength-reduced, if possible.
3506  int round_mask = MinObjAlignmentInBytes - 1;
3507  Node* header_size = NULL;
3508  int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3509  // (T_BYTE has the weakest alignment and size restrictions...)
3510  if (layout_is_con) {
3511    int       hsize  = Klass::layout_helper_header_size(layout_con);
3512    int       eshift = Klass::layout_helper_log2_element_size(layout_con);
3513    BasicType etype  = Klass::layout_helper_element_type(layout_con);
3514    if ((round_mask & ~right_n_bits(eshift)) == 0)
3515      round_mask = 0;  // strength-reduce it if it goes away completely
3516    assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3517    assert(header_size_min <= hsize, "generic minimum is smallest");
3518    header_size_min = hsize;
3519    header_size = intcon(hsize + round_mask);
3520  } else {
3521    Node* hss   = intcon(Klass::_lh_header_size_shift);
3522    Node* hsm   = intcon(Klass::_lh_header_size_mask);
3523    Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3524    hsize       = _gvn.transform( new AndINode(hsize, hsm) );
3525    Node* mask  = intcon(round_mask);
3526    header_size = _gvn.transform( new AddINode(hsize, mask) );
3527  }
3528
3529  Node* elem_shift = NULL;
3530  if (layout_is_con) {
3531    int eshift = Klass::layout_helper_log2_element_size(layout_con);
3532    if (eshift != 0)
3533      elem_shift = intcon(eshift);
3534  } else {
3535    // There is no need to mask or shift this value.
3536    // The semantics of LShiftINode include an implicit mask to 0x1F.
3537    assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
3538    elem_shift = layout_val;
3539  }
3540
3541  // Transition to native address size for all offset calculations:
3542  Node* lengthx = ConvI2X(length);
3543  Node* headerx = ConvI2X(header_size);
3544#ifdef _LP64
3545  { const TypeLong* tllen = _gvn.find_long_type(lengthx);
3546    if (tllen != NULL && tllen->_lo < 0) {
3547      // Add a manual constraint to a positive range.  Cf. array_element_address.
3548      jlong size_max = arrayOopDesc::max_array_length(T_BYTE);
3549      if (size_max > tllen->_hi)  size_max = tllen->_hi;
3550      const TypeLong* tlcon = TypeLong::make(CONST64(0), size_max, Type::WidenMin);
3551      lengthx = _gvn.transform( new ConvI2LNode(length, tlcon));
3552    }
3553  }
3554#endif
3555
3556  // Combine header size (plus rounding) and body size.  Then round down.
3557  // This computation cannot overflow, because it is used only in two
3558  // places, one where the length is sharply limited, and the other
3559  // after a successful allocation.
3560  Node* abody = lengthx;
3561  if (elem_shift != NULL)
3562    abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3563  Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
3564  if (round_mask != 0) {
3565    Node* mask = MakeConX(~round_mask);
3566    size       = _gvn.transform( new AndXNode(size, mask) );
3567  }
3568  // else if round_mask == 0, the size computation is self-rounding
3569
3570  if (return_size_val != NULL) {
3571    // This is the size
3572    (*return_size_val) = size;
3573  }
3574
3575  // Now generate allocation code
3576
3577  // The entire memory state is needed for slow path of the allocation
3578  // since GC and deoptimization can happened.
3579  Node *mem = reset_memory();
3580  set_all_memory(mem); // Create new memory state
3581
3582  // Create the AllocateArrayNode and its result projections
3583  AllocateArrayNode* alloc
3584    = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3585                            control(), mem, i_o(),
3586                            size, klass_node,
3587                            initial_slow_test,
3588                            length);
3589
3590  // Cast to correct type.  Note that the klass_node may be constant or not,
3591  // and in the latter case the actual array type will be inexact also.
3592  // (This happens via a non-constant argument to inline_native_newArray.)
3593  // In any case, the value of klass_node provides the desired array type.
3594  const TypeInt* length_type = _gvn.find_int_type(length);
3595  const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3596  if (ary_type->isa_aryptr() && length_type != NULL) {
3597    // Try to get a better type than POS for the size
3598    ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3599  }
3600
3601  Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3602
3603  // Cast length on remaining path to be as narrow as possible
3604  if (map()->find_edge(length) >= 0) {
3605    Node* ccast = alloc->make_ideal_length(ary_type, &_gvn);
3606    if (ccast != length) {
3607      _gvn.set_type_bottom(ccast);
3608      record_for_igvn(ccast);
3609      replace_in_map(length, ccast);
3610    }
3611  }
3612
3613  return javaoop;
3614}
3615
3616// The following "Ideal_foo" functions are placed here because they recognize
3617// the graph shapes created by the functions immediately above.
3618
3619//---------------------------Ideal_allocation----------------------------------
3620// Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
3621AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
3622  if (ptr == NULL) {     // reduce dumb test in callers
3623    return NULL;
3624  }
3625  if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
3626    ptr = ptr->in(1);
3627    if (ptr == NULL) return NULL;
3628  }
3629  // Return NULL for allocations with several casts:
3630  //   j.l.reflect.Array.newInstance(jobject, jint)
3631  //   Object.clone()
3632  // to keep more precise type from last cast.
3633  if (ptr->is_Proj()) {
3634    Node* allo = ptr->in(0);
3635    if (allo != NULL && allo->is_Allocate()) {
3636      return allo->as_Allocate();
3637    }
3638  }
3639  // Report failure to match.
3640  return NULL;
3641}
3642
3643// Fancy version which also strips off an offset (and reports it to caller).
3644AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,
3645                                             intptr_t& offset) {
3646  Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
3647  if (base == NULL)  return NULL;
3648  return Ideal_allocation(base, phase);
3649}
3650
3651// Trace Initialize <- Proj[Parm] <- Allocate
3652AllocateNode* InitializeNode::allocation() {
3653  Node* rawoop = in(InitializeNode::RawAddress);
3654  if (rawoop->is_Proj()) {
3655    Node* alloc = rawoop->in(0);
3656    if (alloc->is_Allocate()) {
3657      return alloc->as_Allocate();
3658    }
3659  }
3660  return NULL;
3661}
3662
3663// Trace Allocate -> Proj[Parm] -> Initialize
3664InitializeNode* AllocateNode::initialization() {
3665  ProjNode* rawoop = proj_out(AllocateNode::RawAddress);
3666  if (rawoop == NULL)  return NULL;
3667  for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
3668    Node* init = rawoop->fast_out(i);
3669    if (init->is_Initialize()) {
3670      assert(init->as_Initialize()->allocation() == this, "2-way link");
3671      return init->as_Initialize();
3672    }
3673  }
3674  return NULL;
3675}
3676
3677//----------------------------- loop predicates ---------------------------
3678
3679//------------------------------add_predicate_impl----------------------------
3680void GraphKit::add_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {
3681  // Too many traps seen?
3682  if (too_many_traps(reason)) {
3683#ifdef ASSERT
3684    if (TraceLoopPredicate) {
3685      int tc = C->trap_count(reason);
3686      tty->print("too many traps=%s tcount=%d in ",
3687                    Deoptimization::trap_reason_name(reason), tc);
3688      method()->print(); // which method has too many predicate traps
3689      tty->cr();
3690    }
3691#endif
3692    // We cannot afford to take more traps here,
3693    // do not generate predicate.
3694    return;
3695  }
3696
3697  Node *cont    = _gvn.intcon(1);
3698  Node* opq     = _gvn.transform(new Opaque1Node(C, cont));
3699  Node *bol     = _gvn.transform(new Conv2BNode(opq));
3700  IfNode* iff   = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
3701  Node* iffalse = _gvn.transform(new IfFalseNode(iff));
3702  C->add_predicate_opaq(opq);
3703  {
3704    PreserveJVMState pjvms(this);
3705    set_control(iffalse);
3706    inc_sp(nargs);
3707    uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
3708  }
3709  Node* iftrue = _gvn.transform(new IfTrueNode(iff));
3710  set_control(iftrue);
3711}
3712
3713//------------------------------add_predicate---------------------------------
3714void GraphKit::add_predicate(int nargs) {
3715  if (UseLoopPredicate) {
3716    add_predicate_impl(Deoptimization::Reason_predicate, nargs);
3717  }
3718  // loop's limit check predicate should be near the loop.
3719  if (LoopLimitCheck) {
3720    add_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
3721  }
3722}
3723
3724//----------------------------- store barriers ----------------------------
3725#define __ ideal.
3726
3727void GraphKit::sync_kit(IdealKit& ideal) {
3728  set_all_memory(__ merged_memory());
3729  set_i_o(__ i_o());
3730  set_control(__ ctrl());
3731}
3732
3733void GraphKit::final_sync(IdealKit& ideal) {
3734  // Final sync IdealKit and graphKit.
3735  sync_kit(ideal);
3736}
3737
3738Node* GraphKit::byte_map_base_node() {
3739  // Get base of card map
3740  CardTableModRefBS* ct =
3741    barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
3742  assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust users of this code");
3743  if (ct->byte_map_base != NULL) {
3744    return makecon(TypeRawPtr::make((address)ct->byte_map_base));
3745  } else {
3746    return null();
3747  }
3748}
3749
3750// vanilla/CMS post barrier
3751// Insert a write-barrier store.  This is to let generational GC work; we have
3752// to flag all oop-stores before the next GC point.
3753void GraphKit::write_barrier_post(Node* oop_store,
3754                                  Node* obj,
3755                                  Node* adr,
3756                                  uint  adr_idx,
3757                                  Node* val,
3758                                  bool use_precise) {
3759  // No store check needed if we're storing a NULL or an old object
3760  // (latter case is probably a string constant). The concurrent
3761  // mark sweep garbage collector, however, needs to have all nonNull
3762  // oop updates flagged via card-marks.
3763  if (val != NULL && val->is_Con()) {
3764    // must be either an oop or NULL
3765    const Type* t = val->bottom_type();
3766    if (t == TypePtr::NULL_PTR || t == Type::TOP)
3767      // stores of null never (?) need barriers
3768      return;
3769  }
3770
3771  if (use_ReduceInitialCardMarks()
3772      && obj == just_allocated_object(control())) {
3773    // We can skip marks on a freshly-allocated object in Eden.
3774    // Keep this code in sync with new_store_pre_barrier() in runtime.cpp.
3775    // That routine informs GC to take appropriate compensating steps,
3776    // upon a slow-path allocation, so as to make this card-mark
3777    // elision safe.
3778    return;
3779  }
3780
3781  if (!use_precise) {
3782    // All card marks for a (non-array) instance are in one place:
3783    adr = obj;
3784  }
3785  // (Else it's an array (or unknown), and we want more precise card marks.)
3786  assert(adr != NULL, "");
3787
3788  IdealKit ideal(this, true);
3789
3790  // Convert the pointer to an int prior to doing math on it
3791  Node* cast = __ CastPX(__ ctrl(), adr);
3792
3793  // Divide by card size
3794  assert(Universe::heap()->barrier_set()->kind() == BarrierSet::CardTableModRef,
3795         "Only one we handle so far.");
3796  Node* card_offset = __ URShiftX( cast, __ ConI(CardTableModRefBS::card_shift) );
3797
3798  // Combine card table base and card offset
3799  Node* card_adr = __ AddP(__ top(), byte_map_base_node(), card_offset );
3800
3801  // Get the alias_index for raw card-mark memory
3802  int adr_type = Compile::AliasIdxRaw;
3803  Node*   zero = __ ConI(0); // Dirty card value
3804  BasicType bt = T_BYTE;
3805
3806  if (UseCondCardMark) {
3807    // The classic GC reference write barrier is typically implemented
3808    // as a store into the global card mark table.  Unfortunately
3809    // unconditional stores can result in false sharing and excessive
3810    // coherence traffic as well as false transactional aborts.
3811    // UseCondCardMark enables MP "polite" conditional card mark
3812    // stores.  In theory we could relax the load from ctrl() to
3813    // no_ctrl, but that doesn't buy much latitude.
3814    Node* card_val = __ load( __ ctrl(), card_adr, TypeInt::BYTE, bt, adr_type);
3815    __ if_then(card_val, BoolTest::ne, zero);
3816  }
3817
3818  // Smash zero into card
3819  if( !UseConcMarkSweepGC ) {
3820    __ store(__ ctrl(), card_adr, zero, bt, adr_type, MemNode::unordered);
3821  } else {
3822    // Specialized path for CM store barrier
3823    __ storeCM(__ ctrl(), card_adr, zero, oop_store, adr_idx, bt, adr_type);
3824  }
3825
3826  if (UseCondCardMark) {
3827    __ end_if();
3828  }
3829
3830  // Final sync IdealKit and GraphKit.
3831  final_sync(ideal);
3832}
3833/*
3834 * Determine if the G1 pre-barrier can be removed. The pre-barrier is
3835 * required by SATB to make sure all objects live at the start of the
3836 * marking are kept alive, all reference updates need to any previous
3837 * reference stored before writing.
3838 *
3839 * If the previous value is NULL there is no need to save the old value.
3840 * References that are NULL are filtered during runtime by the barrier
3841 * code to avoid unnecessary queuing.
3842 *
3843 * However in the case of newly allocated objects it might be possible to
3844 * prove that the reference about to be overwritten is NULL during compile
3845 * time and avoid adding the barrier code completely.
3846 *
3847 * The compiler needs to determine that the object in which a field is about
3848 * to be written is newly allocated, and that no prior store to the same field
3849 * has happened since the allocation.
3850 *
3851 * Returns true if the pre-barrier can be removed
3852 */
3853bool GraphKit::g1_can_remove_pre_barrier(PhaseTransform* phase, Node* adr,
3854                                         BasicType bt, uint adr_idx) {
3855  intptr_t offset = 0;
3856  Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
3857  AllocateNode* alloc = AllocateNode::Ideal_allocation(base, phase);
3858
3859  if (offset == Type::OffsetBot) {
3860    return false; // cannot unalias unless there are precise offsets
3861  }
3862
3863  if (alloc == NULL) {
3864    return false; // No allocation found
3865  }
3866
3867  intptr_t size_in_bytes = type2aelembytes(bt);
3868
3869  Node* mem = memory(adr_idx); // start searching here...
3870
3871  for (int cnt = 0; cnt < 50; cnt++) {
3872
3873    if (mem->is_Store()) {
3874
3875      Node* st_adr = mem->in(MemNode::Address);
3876      intptr_t st_offset = 0;
3877      Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
3878
3879      if (st_base == NULL) {
3880        break; // inscrutable pointer
3881      }
3882
3883      // Break we have found a store with same base and offset as ours so break
3884      if (st_base == base && st_offset == offset) {
3885        break;
3886      }
3887
3888      if (st_offset != offset && st_offset != Type::OffsetBot) {
3889        const int MAX_STORE = BytesPerLong;
3890        if (st_offset >= offset + size_in_bytes ||
3891            st_offset <= offset - MAX_STORE ||
3892            st_offset <= offset - mem->as_Store()->memory_size()) {
3893          // Success:  The offsets are provably independent.
3894          // (You may ask, why not just test st_offset != offset and be done?
3895          // The answer is that stores of different sizes can co-exist
3896          // in the same sequence of RawMem effects.  We sometimes initialize
3897          // a whole 'tile' of array elements with a single jint or jlong.)
3898          mem = mem->in(MemNode::Memory);
3899          continue; // advance through independent store memory
3900        }
3901      }
3902
3903      if (st_base != base
3904          && MemNode::detect_ptr_independence(base, alloc, st_base,
3905                                              AllocateNode::Ideal_allocation(st_base, phase),
3906                                              phase)) {
3907        // Success:  The bases are provably independent.
3908        mem = mem->in(MemNode::Memory);
3909        continue; // advance through independent store memory
3910      }
3911    } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
3912
3913      InitializeNode* st_init = mem->in(0)->as_Initialize();
3914      AllocateNode* st_alloc = st_init->allocation();
3915
3916      // Make sure that we are looking at the same allocation site.
3917      // The alloc variable is guaranteed to not be null here from earlier check.
3918      if (alloc == st_alloc) {
3919        // Check that the initialization is storing NULL so that no previous store
3920        // has been moved up and directly write a reference
3921        Node* captured_store = st_init->find_captured_store(offset,
3922                                                            type2aelembytes(T_OBJECT),
3923                                                            phase);
3924        if (captured_store == NULL || captured_store == st_init->zero_memory()) {
3925          return true;
3926        }
3927      }
3928    }
3929
3930    // Unless there is an explicit 'continue', we must bail out here,
3931    // because 'mem' is an inscrutable memory state (e.g., a call).
3932    break;
3933  }
3934
3935  return false;
3936}
3937
3938// G1 pre/post barriers
3939void GraphKit::g1_write_barrier_pre(bool do_load,
3940                                    Node* obj,
3941                                    Node* adr,
3942                                    uint alias_idx,
3943                                    Node* val,
3944                                    const TypeOopPtr* val_type,
3945                                    Node* pre_val,
3946                                    BasicType bt) {
3947
3948  // Some sanity checks
3949  // Note: val is unused in this routine.
3950
3951  if (do_load) {
3952    // We need to generate the load of the previous value
3953    assert(obj != NULL, "must have a base");
3954    assert(adr != NULL, "where are loading from?");
3955    assert(pre_val == NULL, "loaded already?");
3956    assert(val_type != NULL, "need a type");
3957
3958    if (use_ReduceInitialCardMarks()
3959        && g1_can_remove_pre_barrier(&_gvn, adr, bt, alias_idx)) {
3960      return;
3961    }
3962
3963  } else {
3964    // In this case both val_type and alias_idx are unused.
3965    assert(pre_val != NULL, "must be loaded already");
3966    // Nothing to be done if pre_val is null.
3967    if (pre_val->bottom_type() == TypePtr::NULL_PTR) return;
3968    assert(pre_val->bottom_type()->basic_type() == T_OBJECT, "or we shouldn't be here");
3969  }
3970  assert(bt == T_OBJECT, "or we shouldn't be here");
3971
3972  IdealKit ideal(this, true);
3973
3974  Node* tls = __ thread(); // ThreadLocalStorage
3975
3976  Node* no_ctrl = NULL;
3977  Node* no_base = __ top();
3978  Node* zero  = __ ConI(0);
3979  Node* zeroX = __ ConX(0);
3980
3981  float likely  = PROB_LIKELY(0.999);
3982  float unlikely  = PROB_UNLIKELY(0.999);
3983
3984  BasicType active_type = in_bytes(PtrQueue::byte_width_of_active()) == 4 ? T_INT : T_BYTE;
3985  assert(in_bytes(PtrQueue::byte_width_of_active()) == 4 || in_bytes(PtrQueue::byte_width_of_active()) == 1, "flag width");
3986
3987  // Offsets into the thread
3988  const int marking_offset = in_bytes(JavaThread::satb_mark_queue_offset() +  // 648
3989                                          PtrQueue::byte_offset_of_active());
3990  const int index_offset   = in_bytes(JavaThread::satb_mark_queue_offset() +  // 656
3991                                          PtrQueue::byte_offset_of_index());
3992  const int buffer_offset  = in_bytes(JavaThread::satb_mark_queue_offset() +  // 652
3993                                          PtrQueue::byte_offset_of_buf());
3994
3995  // Now the actual pointers into the thread
3996  Node* marking_adr = __ AddP(no_base, tls, __ ConX(marking_offset));
3997  Node* buffer_adr  = __ AddP(no_base, tls, __ ConX(buffer_offset));
3998  Node* index_adr   = __ AddP(no_base, tls, __ ConX(index_offset));
3999
4000  // Now some of the values
4001  Node* marking = __ load(__ ctrl(), marking_adr, TypeInt::INT, active_type, Compile::AliasIdxRaw);
4002
4003  // if (!marking)
4004  __ if_then(marking, BoolTest::ne, zero, unlikely); {
4005    BasicType index_bt = TypeX_X->basic_type();
4006    assert(sizeof(size_t) == type2aelembytes(index_bt), "Loading G1 PtrQueue::_index with wrong size.");
4007    Node* index   = __ load(__ ctrl(), index_adr, TypeX_X, index_bt, Compile::AliasIdxRaw);
4008
4009    if (do_load) {
4010      // load original value
4011      // alias_idx correct??
4012      pre_val = __ load(__ ctrl(), adr, val_type, bt, alias_idx);
4013    }
4014
4015    // if (pre_val != NULL)
4016    __ if_then(pre_val, BoolTest::ne, null()); {
4017      Node* buffer  = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
4018
4019      // is the queue for this thread full?
4020      __ if_then(index, BoolTest::ne, zeroX, likely); {
4021
4022        // decrement the index
4023        Node* next_index = _gvn.transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
4024
4025        // Now get the buffer location we will log the previous value into and store it
4026        Node *log_addr = __ AddP(no_base, buffer, next_index);
4027        __ store(__ ctrl(), log_addr, pre_val, T_OBJECT, Compile::AliasIdxRaw, MemNode::unordered);
4028        // update the index
4029        __ store(__ ctrl(), index_adr, next_index, index_bt, Compile::AliasIdxRaw, MemNode::unordered);
4030
4031      } __ else_(); {
4032
4033        // logging buffer is full, call the runtime
4034        const TypeFunc *tf = OptoRuntime::g1_wb_pre_Type();
4035        __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), "g1_wb_pre", pre_val, tls);
4036      } __ end_if();  // (!index)
4037    } __ end_if();  // (pre_val != NULL)
4038  } __ end_if();  // (!marking)
4039
4040  // Final sync IdealKit and GraphKit.
4041  final_sync(ideal);
4042}
4043
4044/*
4045 * G1 similar to any GC with a Young Generation requires a way to keep track of
4046 * references from Old Generation to Young Generation to make sure all live
4047 * objects are found. G1 also requires to keep track of object references
4048 * between different regions to enable evacuation of old regions, which is done
4049 * as part of mixed collections. References are tracked in remembered sets and
4050 * is continuously updated as reference are written to with the help of the
4051 * post-barrier.
4052 *
4053 * To reduce the number of updates to the remembered set the post-barrier
4054 * filters updates to fields in objects located in the Young Generation,
4055 * the same region as the reference, when the NULL is being written or
4056 * if the card is already marked as dirty by an earlier write.
4057 *
4058 * Under certain circumstances it is possible to avoid generating the
4059 * post-barrier completely if it is possible during compile time to prove
4060 * the object is newly allocated and that no safepoint exists between the
4061 * allocation and the store.
4062 *
4063 * In the case of slow allocation the allocation code must handle the barrier
4064 * as part of the allocation in the case the allocated object is not located
4065 * in the nursery, this would happen for humongous objects. This is similar to
4066 * how CMS is required to handle this case, see the comments for the method
4067 * CollectedHeap::new_store_pre_barrier and OptoRuntime::new_store_pre_barrier.
4068 * A deferred card mark is required for these objects and handled in the above
4069 * mentioned methods.
4070 *
4071 * Returns true if the post barrier can be removed
4072 */
4073bool GraphKit::g1_can_remove_post_barrier(PhaseTransform* phase, Node* store,
4074                                          Node* adr) {
4075  intptr_t      offset = 0;
4076  Node*         base   = AddPNode::Ideal_base_and_offset(adr, phase, offset);
4077  AllocateNode* alloc  = AllocateNode::Ideal_allocation(base, phase);
4078
4079  if (offset == Type::OffsetBot) {
4080    return false; // cannot unalias unless there are precise offsets
4081  }
4082
4083  if (alloc == NULL) {
4084     return false; // No allocation found
4085  }
4086
4087  // Start search from Store node
4088  Node* mem = store->in(MemNode::Control);
4089  if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
4090
4091    InitializeNode* st_init = mem->in(0)->as_Initialize();
4092    AllocateNode*  st_alloc = st_init->allocation();
4093
4094    // Make sure we are looking at the same allocation
4095    if (alloc == st_alloc) {
4096      return true;
4097    }
4098  }
4099
4100  return false;
4101}
4102
4103//
4104// Update the card table and add card address to the queue
4105//
4106void GraphKit::g1_mark_card(IdealKit& ideal,
4107                            Node* card_adr,
4108                            Node* oop_store,
4109                            uint oop_alias_idx,
4110                            Node* index,
4111                            Node* index_adr,
4112                            Node* buffer,
4113                            const TypeFunc* tf) {
4114
4115  Node* zero  = __ ConI(0);
4116  Node* zeroX = __ ConX(0);
4117  Node* no_base = __ top();
4118  BasicType card_bt = T_BYTE;
4119  // Smash zero into card. MUST BE ORDERED WRT TO STORE
4120  __ storeCM(__ ctrl(), card_adr, zero, oop_store, oop_alias_idx, card_bt, Compile::AliasIdxRaw);
4121
4122  //  Now do the queue work
4123  __ if_then(index, BoolTest::ne, zeroX); {
4124
4125    Node* next_index = _gvn.transform(new SubXNode(index, __ ConX(sizeof(intptr_t))));
4126    Node* log_addr = __ AddP(no_base, buffer, next_index);
4127
4128    // Order, see storeCM.
4129    __ store(__ ctrl(), log_addr, card_adr, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);
4130    __ store(__ ctrl(), index_adr, next_index, TypeX_X->basic_type(), Compile::AliasIdxRaw, MemNode::unordered);
4131
4132  } __ else_(); {
4133    __ make_leaf_call(tf, CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), "g1_wb_post", card_adr, __ thread());
4134  } __ end_if();
4135
4136}
4137
4138void GraphKit::g1_write_barrier_post(Node* oop_store,
4139                                     Node* obj,
4140                                     Node* adr,
4141                                     uint alias_idx,
4142                                     Node* val,
4143                                     BasicType bt,
4144                                     bool use_precise) {
4145  // If we are writing a NULL then we need no post barrier
4146
4147  if (val != NULL && val->is_Con() && val->bottom_type() == TypePtr::NULL_PTR) {
4148    // Must be NULL
4149    const Type* t = val->bottom_type();
4150    assert(t == Type::TOP || t == TypePtr::NULL_PTR, "must be NULL");
4151    // No post barrier if writing NULLx
4152    return;
4153  }
4154
4155  if (use_ReduceInitialCardMarks() && obj == just_allocated_object(control())) {
4156    // We can skip marks on a freshly-allocated object in Eden.
4157    // Keep this code in sync with new_store_pre_barrier() in runtime.cpp.
4158    // That routine informs GC to take appropriate compensating steps,
4159    // upon a slow-path allocation, so as to make this card-mark
4160    // elision safe.
4161    return;
4162  }
4163
4164  if (use_ReduceInitialCardMarks()
4165      && g1_can_remove_post_barrier(&_gvn, oop_store, adr)) {
4166    return;
4167  }
4168
4169  if (!use_precise) {
4170    // All card marks for a (non-array) instance are in one place:
4171    adr = obj;
4172  }
4173  // (Else it's an array (or unknown), and we want more precise card marks.)
4174  assert(adr != NULL, "");
4175
4176  IdealKit ideal(this, true);
4177
4178  Node* tls = __ thread(); // ThreadLocalStorage
4179
4180  Node* no_base = __ top();
4181  float likely  = PROB_LIKELY(0.999);
4182  float unlikely  = PROB_UNLIKELY(0.999);
4183  Node* young_card = __ ConI((jint)G1SATBCardTableModRefBS::g1_young_card_val());
4184  Node* dirty_card = __ ConI((jint)CardTableModRefBS::dirty_card_val());
4185  Node* zeroX = __ ConX(0);
4186
4187  // Get the alias_index for raw card-mark memory
4188  const TypePtr* card_type = TypeRawPtr::BOTTOM;
4189
4190  const TypeFunc *tf = OptoRuntime::g1_wb_post_Type();
4191
4192  // Offsets into the thread
4193  const int index_offset  = in_bytes(JavaThread::dirty_card_queue_offset() +
4194                                     PtrQueue::byte_offset_of_index());
4195  const int buffer_offset = in_bytes(JavaThread::dirty_card_queue_offset() +
4196                                     PtrQueue::byte_offset_of_buf());
4197
4198  // Pointers into the thread
4199
4200  Node* buffer_adr = __ AddP(no_base, tls, __ ConX(buffer_offset));
4201  Node* index_adr =  __ AddP(no_base, tls, __ ConX(index_offset));
4202
4203  // Now some values
4204  // Use ctrl to avoid hoisting these values past a safepoint, which could
4205  // potentially reset these fields in the JavaThread.
4206  Node* index  = __ load(__ ctrl(), index_adr, TypeX_X, TypeX_X->basic_type(), Compile::AliasIdxRaw);
4207  Node* buffer = __ load(__ ctrl(), buffer_adr, TypeRawPtr::NOTNULL, T_ADDRESS, Compile::AliasIdxRaw);
4208
4209  // Convert the store obj pointer to an int prior to doing math on it
4210  // Must use ctrl to prevent "integerized oop" existing across safepoint
4211  Node* cast =  __ CastPX(__ ctrl(), adr);
4212
4213  // Divide pointer by card size
4214  Node* card_offset = __ URShiftX( cast, __ ConI(CardTableModRefBS::card_shift) );
4215
4216  // Combine card table base and card offset
4217  Node* card_adr = __ AddP(no_base, byte_map_base_node(), card_offset );
4218
4219  // If we know the value being stored does it cross regions?
4220
4221  if (val != NULL) {
4222    // Does the store cause us to cross regions?
4223
4224    // Should be able to do an unsigned compare of region_size instead of
4225    // and extra shift. Do we have an unsigned compare??
4226    // Node* region_size = __ ConI(1 << HeapRegion::LogOfHRGrainBytes);
4227    Node* xor_res =  __ URShiftX ( __ XorX( cast,  __ CastPX(__ ctrl(), val)), __ ConI(HeapRegion::LogOfHRGrainBytes));
4228
4229    // if (xor_res == 0) same region so skip
4230    __ if_then(xor_res, BoolTest::ne, zeroX); {
4231
4232      // No barrier if we are storing a NULL
4233      __ if_then(val, BoolTest::ne, null(), unlikely); {
4234
4235        // Ok must mark the card if not already dirty
4236
4237        // load the original value of the card
4238        Node* card_val = __ load(__ ctrl(), card_adr, TypeInt::INT, T_BYTE, Compile::AliasIdxRaw);
4239
4240        __ if_then(card_val, BoolTest::ne, young_card); {
4241          sync_kit(ideal);
4242          // Use Op_MemBarVolatile to achieve the effect of a StoreLoad barrier.
4243          insert_mem_bar(Op_MemBarVolatile, oop_store);
4244          __ sync_kit(this);
4245
4246          Node* card_val_reload = __ load(__ ctrl(), card_adr, TypeInt::INT, T_BYTE, Compile::AliasIdxRaw);
4247          __ if_then(card_val_reload, BoolTest::ne, dirty_card); {
4248            g1_mark_card(ideal, card_adr, oop_store, alias_idx, index, index_adr, buffer, tf);
4249          } __ end_if();
4250        } __ end_if();
4251      } __ end_if();
4252    } __ end_if();
4253  } else {
4254    // Object.clone() instrinsic uses this path.
4255    g1_mark_card(ideal, card_adr, oop_store, alias_idx, index, index_adr, buffer, tf);
4256  }
4257
4258  // Final sync IdealKit and GraphKit.
4259  final_sync(ideal);
4260}
4261#undef __
4262
4263
4264
4265Node* GraphKit::load_String_offset(Node* ctrl, Node* str) {
4266  if (java_lang_String::has_offset_field()) {
4267    int offset_offset = java_lang_String::offset_offset_in_bytes();
4268    const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4269                                                       false, NULL, 0);
4270    const TypePtr* offset_field_type = string_type->add_offset(offset_offset);
4271    int offset_field_idx = C->get_alias_index(offset_field_type);
4272    return make_load(ctrl,
4273                     basic_plus_adr(str, str, offset_offset),
4274                     TypeInt::INT, T_INT, offset_field_idx, MemNode::unordered);
4275  } else {
4276    return intcon(0);
4277  }
4278}
4279
4280Node* GraphKit::load_String_length(Node* ctrl, Node* str) {
4281  if (java_lang_String::has_count_field()) {
4282    int count_offset = java_lang_String::count_offset_in_bytes();
4283    const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4284                                                       false, NULL, 0);
4285    const TypePtr* count_field_type = string_type->add_offset(count_offset);
4286    int count_field_idx = C->get_alias_index(count_field_type);
4287    return make_load(ctrl,
4288                     basic_plus_adr(str, str, count_offset),
4289                     TypeInt::INT, T_INT, count_field_idx, MemNode::unordered);
4290  } else {
4291    return load_array_length(load_String_value(ctrl, str));
4292  }
4293}
4294
4295Node* GraphKit::load_String_value(Node* ctrl, Node* str) {
4296  int value_offset = java_lang_String::value_offset_in_bytes();
4297  const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4298                                                     false, NULL, 0);
4299  const TypePtr* value_field_type = string_type->add_offset(value_offset);
4300  const TypeAryPtr*  value_type = TypeAryPtr::make(TypePtr::NotNull,
4301                                                   TypeAry::make(TypeInt::CHAR,TypeInt::POS),
4302                                                   ciTypeArrayKlass::make(T_CHAR), true, 0);
4303  int value_field_idx = C->get_alias_index(value_field_type);
4304  Node* load = make_load(ctrl, basic_plus_adr(str, str, value_offset),
4305                         value_type, T_OBJECT, value_field_idx, MemNode::unordered);
4306  // String.value field is known to be @Stable.
4307  if (UseImplicitStableValues) {
4308    load = cast_array_to_stable(load, value_type);
4309  }
4310  return load;
4311}
4312
4313void GraphKit::store_String_offset(Node* ctrl, Node* str, Node* value) {
4314  int offset_offset = java_lang_String::offset_offset_in_bytes();
4315  const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4316                                                     false, NULL, 0);
4317  const TypePtr* offset_field_type = string_type->add_offset(offset_offset);
4318  int offset_field_idx = C->get_alias_index(offset_field_type);
4319  store_to_memory(ctrl, basic_plus_adr(str, offset_offset),
4320                  value, T_INT, offset_field_idx, MemNode::unordered);
4321}
4322
4323void GraphKit::store_String_value(Node* ctrl, Node* str, Node* value) {
4324  int value_offset = java_lang_String::value_offset_in_bytes();
4325  const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4326                                                     false, NULL, 0);
4327  const TypePtr* value_field_type = string_type->add_offset(value_offset);
4328
4329  store_oop_to_object(ctrl, str,  basic_plus_adr(str, value_offset), value_field_type,
4330      value, TypeAryPtr::CHARS, T_OBJECT, MemNode::unordered);
4331}
4332
4333void GraphKit::store_String_length(Node* ctrl, Node* str, Node* value) {
4334  int count_offset = java_lang_String::count_offset_in_bytes();
4335  const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4336                                                     false, NULL, 0);
4337  const TypePtr* count_field_type = string_type->add_offset(count_offset);
4338  int count_field_idx = C->get_alias_index(count_field_type);
4339  store_to_memory(ctrl, basic_plus_adr(str, count_offset),
4340                  value, T_INT, count_field_idx, MemNode::unordered);
4341}
4342
4343Node* GraphKit::cast_array_to_stable(Node* ary, const TypeAryPtr* ary_type) {
4344  // Reify the property as a CastPP node in Ideal graph to comply with monotonicity
4345  // assumption of CCP analysis.
4346  return _gvn.transform(new CastPPNode(ary, ary_type->cast_to_stable(true)));
4347}
4348