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