1 /*
   2  * Copyright (c) 1999, 2016, 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 "asm/macroAssembler.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "oops/objArrayKlass.hpp"
  32 #include "opto/addnode.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/c2compiler.hpp"
  35 #include "opto/callGenerator.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/convertnode.hpp"
  39 #include "opto/countbitsnode.hpp"
  40 #include "opto/intrinsicnode.hpp"
  41 #include "opto/idealKit.hpp"
  42 #include "opto/mathexactnode.hpp"
  43 #include "opto/movenode.hpp"
  44 #include "opto/mulnode.hpp"
  45 #include "opto/narrowptrnode.hpp"
  46 #include "opto/opaquenode.hpp"
  47 #include "opto/parse.hpp"
  48 #include "opto/runtime.hpp"
  49 #include "opto/subnode.hpp"
  50 #include "prims/nativeLookup.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "trace/traceMacros.hpp"
  53 
  54 class LibraryIntrinsic : public InlineCallGenerator {
  55   // Extend the set of intrinsics known to the runtime:
  56  public:
  57  private:
  58   bool             _is_virtual;
  59   bool             _does_virtual_dispatch;
  60   int8_t           _predicates_count;  // Intrinsic is predicated by several conditions
  61   int8_t           _last_predicate; // Last generated predicate
  62   vmIntrinsics::ID _intrinsic_id;
  63 
  64  public:
  65   LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)
  66     : InlineCallGenerator(m),
  67       _is_virtual(is_virtual),
  68       _does_virtual_dispatch(does_virtual_dispatch),
  69       _predicates_count((int8_t)predicates_count),
  70       _last_predicate((int8_t)-1),
  71       _intrinsic_id(id)
  72   {
  73   }
  74   virtual bool is_intrinsic() const { return true; }
  75   virtual bool is_virtual()   const { return _is_virtual; }
  76   virtual bool is_predicated() const { return _predicates_count > 0; }
  77   virtual int  predicates_count() const { return _predicates_count; }
  78   virtual bool does_virtual_dispatch()   const { return _does_virtual_dispatch; }
  79   virtual JVMState* generate(JVMState* jvms);
  80   virtual Node* generate_predicate(JVMState* jvms, int predicate);
  81   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
  82 };
  83 
  84 
  85 // Local helper class for LibraryIntrinsic:
  86 class LibraryCallKit : public GraphKit {
  87  private:
  88   LibraryIntrinsic* _intrinsic;     // the library intrinsic being called
  89   Node*             _result;        // the result node, if any
  90   int               _reexecute_sp;  // the stack pointer when bytecode needs to be reexecuted
  91 
  92   const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);
  93 
  94  public:
  95   LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)
  96     : GraphKit(jvms),
  97       _intrinsic(intrinsic),
  98       _result(NULL)
  99   {
 100     // Check if this is a root compile.  In that case we don't have a caller.
 101     if (!jvms->has_method()) {
 102       _reexecute_sp = sp();
 103     } else {
 104       // Find out how many arguments the interpreter needs when deoptimizing
 105       // and save the stack pointer value so it can used by uncommon_trap.
 106       // We find the argument count by looking at the declared signature.
 107       bool ignored_will_link;
 108       ciSignature* declared_signature = NULL;
 109       ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
 110       const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));
 111       _reexecute_sp = sp() + nargs;  // "push" arguments back on stack
 112     }
 113   }
 114 
 115   virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }
 116 
 117   ciMethod*         caller()    const    { return jvms()->method(); }
 118   int               bci()       const    { return jvms()->bci(); }
 119   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
 120   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
 121   ciMethod*         callee()    const    { return _intrinsic->method(); }
 122 
 123   bool  try_to_inline(int predicate);
 124   Node* try_to_predicate(int predicate);
 125 
 126   void push_result() {
 127     // Push the result onto the stack.
 128     if (!stopped() && result() != NULL) {
 129       BasicType bt = result()->bottom_type()->basic_type();
 130       push_node(bt, result());
 131     }
 132   }
 133 
 134  private:
 135   void fatal_unexpected_iid(vmIntrinsics::ID iid) {
 136     fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
 137   }
 138 
 139   void  set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }
 140   void  set_result(RegionNode* region, PhiNode* value);
 141   Node*     result() { return _result; }
 142 
 143   virtual int reexecute_sp() { return _reexecute_sp; }
 144 
 145   // Helper functions to inline natives
 146   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
 147   Node* generate_slow_guard(Node* test, RegionNode* region);
 148   Node* generate_fair_guard(Node* test, RegionNode* region);
 149   Node* generate_negative_guard(Node* index, RegionNode* region,
 150                                 // resulting CastII of index:
 151                                 Node* *pos_index = NULL);
 152   Node* generate_limit_guard(Node* offset, Node* subseq_length,
 153                              Node* array_length,
 154                              RegionNode* region);
 155   void  generate_string_range_check(Node* array, Node* offset,
 156                                     Node* length, bool char_count);
 157   Node* generate_current_thread(Node* &tls_output);
 158   Node* load_mirror_from_klass(Node* klass);
 159   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
 160                                       RegionNode* region, int null_path,
 161                                       int offset);
 162   Node* load_klass_from_mirror(Node* mirror, bool never_see_null,
 163                                RegionNode* region, int null_path) {
 164     int offset = java_lang_Class::klass_offset_in_bytes();
 165     return load_klass_from_mirror_common(mirror, never_see_null,
 166                                          region, null_path,
 167                                          offset);
 168   }
 169   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
 170                                      RegionNode* region, int null_path) {
 171     int offset = java_lang_Class::array_klass_offset_in_bytes();
 172     return load_klass_from_mirror_common(mirror, never_see_null,
 173                                          region, null_path,
 174                                          offset);
 175   }
 176   Node* generate_access_flags_guard(Node* kls,
 177                                     int modifier_mask, int modifier_bits,
 178                                     RegionNode* region);
 179   Node* generate_interface_guard(Node* kls, RegionNode* region);
 180   Node* generate_array_guard(Node* kls, RegionNode* region) {
 181     return generate_array_guard_common(kls, region, false, false);
 182   }
 183   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
 184     return generate_array_guard_common(kls, region, false, true);
 185   }
 186   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
 187     return generate_array_guard_common(kls, region, true, false);
 188   }
 189   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
 190     return generate_array_guard_common(kls, region, true, true);
 191   }
 192   Node* generate_array_guard_common(Node* kls, RegionNode* region,
 193                                     bool obj_array, bool not_array);
 194   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
 195   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
 196                                      bool is_virtual = false, bool is_static = false);
 197   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
 198     return generate_method_call(method_id, false, true);
 199   }
 200   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
 201     return generate_method_call(method_id, true, false);
 202   }
 203   Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static, ciInstanceKlass * fromKls);
 204   Node * field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static, ciInstanceKlass * fromKls);
 205 
 206   Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae);
 207   bool inline_string_compareTo(StrIntrinsicNode::ArgEnc ae);
 208   bool inline_string_indexOf(StrIntrinsicNode::ArgEnc ae);
 209   bool inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae);
 210   Node* make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
 211                           RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae);
 212   bool inline_string_indexOfChar();
 213   bool inline_string_equals(StrIntrinsicNode::ArgEnc ae);
 214   bool inline_string_toBytesU();
 215   bool inline_string_getCharsU();
 216   bool inline_string_copy(bool compress);
 217   bool inline_string_char_access(bool is_store);
 218   Node* round_double_node(Node* n);
 219   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
 220   bool inline_math_native(vmIntrinsics::ID id);
 221   bool inline_trig(vmIntrinsics::ID id);
 222   bool inline_math(vmIntrinsics::ID id);
 223   template <typename OverflowOp>
 224   bool inline_math_overflow(Node* arg1, Node* arg2);
 225   void inline_math_mathExact(Node* math, Node* test);
 226   bool inline_math_addExactI(bool is_increment);
 227   bool inline_math_addExactL(bool is_increment);
 228   bool inline_math_multiplyExactI();
 229   bool inline_math_multiplyExactL();
 230   bool inline_math_negateExactI();
 231   bool inline_math_negateExactL();
 232   bool inline_math_subtractExactI(bool is_decrement);
 233   bool inline_math_subtractExactL(bool is_decrement);
 234   bool inline_min_max(vmIntrinsics::ID id);
 235   bool inline_notify(vmIntrinsics::ID id);
 236   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
 237   // This returns Type::AnyPtr, RawPtr, or OopPtr.
 238   int classify_unsafe_addr(Node* &base, Node* &offset);
 239   Node* make_unsafe_address(Node* base, Node* offset);
 240   // Helper for inline_unsafe_access.
 241   // Generates the guards that check whether the result of
 242   // Unsafe.getObject should be recorded in an SATB log buffer.
 243   void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
 244 
 245   typedef enum { Relaxed, Opaque, Volatile, Acquire, Release } AccessKind;
 246   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, AccessKind kind, bool is_unaligned);
 247   static bool klass_needs_init_guard(Node* kls);
 248   bool inline_unsafe_allocate();
 249   bool inline_unsafe_copyMemory();
 250   bool inline_native_currentThread();
 251 #ifdef TRACE_HAVE_INTRINSICS
 252   bool inline_native_classID();
 253   bool inline_native_threadID();
 254 #endif
 255   bool inline_native_time_funcs(address method, const char* funcName);
 256   bool inline_native_isInterrupted();
 257   bool inline_native_Class_query(vmIntrinsics::ID id);
 258   bool inline_native_subtype_check();
 259 
 260   bool inline_native_newArray();
 261   bool inline_native_getLength();
 262   bool inline_array_copyOf(bool is_copyOfRange);
 263   bool inline_array_equals(StrIntrinsicNode::ArgEnc ae);
 264   bool inline_objects_checkIndex();
 265   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
 266   bool inline_native_clone(bool is_virtual);
 267   bool inline_native_Reflection_getCallerClass();
 268   // Helper function for inlining native object hash method
 269   bool inline_native_hashcode(bool is_virtual, bool is_static);
 270   bool inline_native_getClass();
 271 
 272   // Helper functions for inlining arraycopy
 273   bool inline_arraycopy();
 274   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
 275                                                 RegionNode* slow_region);
 276   JVMState* arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp);
 277   void arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp);
 278 
 279   typedef enum { LS_get_add, LS_get_set, LS_cmp_swap, LS_cmp_swap_weak, LS_cmp_exchange } LoadStoreKind;
 280   MemNode::MemOrd access_kind_to_memord_LS(AccessKind access_kind, bool is_store);
 281   MemNode::MemOrd access_kind_to_memord(AccessKind access_kind);
 282   bool inline_unsafe_load_store(BasicType type,  LoadStoreKind kind, AccessKind access_kind);
 283   bool inline_unsafe_fence(vmIntrinsics::ID id);
 284   bool inline_fp_conversions(vmIntrinsics::ID id);
 285   bool inline_number_methods(vmIntrinsics::ID id);
 286   bool inline_reference_get();
 287   bool inline_Class_cast();
 288   bool inline_aescrypt_Block(vmIntrinsics::ID id);
 289   bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);
 290   bool inline_counterMode_AESCrypt(vmIntrinsics::ID id);
 291   Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);
 292   Node* inline_counterMode_AESCrypt_predicate();
 293   Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);
 294   Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);
 295   bool inline_ghash_processBlocks();
 296   bool inline_sha_implCompress(vmIntrinsics::ID id);
 297   bool inline_digestBase_implCompressMB(int predicate);
 298   bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,
 299                                  bool long_state, address stubAddr, const char *stubName,
 300                                  Node* src_start, Node* ofs, Node* limit);
 301   Node* get_state_from_sha_object(Node *sha_object);
 302   Node* get_state_from_sha5_object(Node *sha_object);
 303   Node* inline_digestBase_implCompressMB_predicate(int predicate);
 304   bool inline_encodeISOArray();
 305   bool inline_updateCRC32();
 306   bool inline_updateBytesCRC32();
 307   bool inline_updateByteBufferCRC32();
 308   Node* get_table_from_crc32c_class(ciInstanceKlass *crc32c_class);
 309   bool inline_updateBytesCRC32C();
 310   bool inline_updateDirectByteBufferCRC32C();
 311   bool inline_updateBytesAdler32();
 312   bool inline_updateByteBufferAdler32();
 313   bool inline_multiplyToLen();
 314   bool inline_hasNegatives();
 315   bool inline_squareToLen();
 316   bool inline_mulAdd();
 317   bool inline_montgomeryMultiply();
 318   bool inline_montgomerySquare();
 319   bool inline_vectorizedMismatch();
 320 
 321   bool inline_profileBoolean();
 322   bool inline_isCompileConstant();
 323 
 324   bool inline_deoptimize();
 325 };
 326 
 327 //---------------------------make_vm_intrinsic----------------------------
 328 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
 329   vmIntrinsics::ID id = m->intrinsic_id();
 330   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
 331 
 332   if (!m->is_loaded()) {
 333     // Do not attempt to inline unloaded methods.
 334     return NULL;
 335   }
 336 
 337   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
 338   bool is_available = false;
 339 
 340   {
 341     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
 342     // the compiler must transition to '_thread_in_vm' state because both
 343     // methods access VM-internal data.
 344     VM_ENTRY_MARK;
 345     methodHandle mh(THREAD, m->get_Method());
 346     is_available = compiler->is_intrinsic_supported(mh, is_virtual) &&
 347                    !C->directive()->is_intrinsic_disabled(mh) &&
 348                    !vmIntrinsics::is_disabled_by_flags(mh);
 349 
 350   }
 351 
 352   if (is_available) {
 353     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 354     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 355     return new LibraryIntrinsic(m, is_virtual,
 356                                 vmIntrinsics::predicates_needed(id),
 357                                 vmIntrinsics::does_virtual_dispatch(id),
 358                                 (vmIntrinsics::ID) id);
 359   } else {
 360     return NULL;
 361   }
 362 }
 363 
 364 //----------------------register_library_intrinsics-----------------------
 365 // Initialize this file's data structures, for each Compile instance.
 366 void Compile::register_library_intrinsics() {
 367   // Nothing to do here.
 368 }
 369 
 370 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 371   LibraryCallKit kit(jvms, this);
 372   Compile* C = kit.C;
 373   int nodes = C->unique();
 374 #ifndef PRODUCT
 375   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 376     char buf[1000];
 377     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 378     tty->print_cr("Intrinsic %s", str);
 379   }
 380 #endif
 381   ciMethod* callee = kit.callee();
 382   const int bci    = kit.bci();
 383 
 384   // Try to inline the intrinsic.
 385   if ((CheckIntrinsics ? callee->intrinsic_candidate() : true) &&
 386       kit.try_to_inline(_last_predicate)) {
 387     if (C->print_intrinsics() || C->print_inlining()) {
 388       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
 389     }
 390     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 391     if (C->log()) {
 392       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 393                      vmIntrinsics::name_at(intrinsic_id()),
 394                      (is_virtual() ? " virtual='1'" : ""),
 395                      C->unique() - nodes);
 396     }
 397     // Push the result from the inlined method onto the stack.
 398     kit.push_result();
 399     C->print_inlining_update(this);
 400     return kit.transfer_exceptions_into_jvms();
 401   }
 402 
 403   // The intrinsic bailed out
 404   if (C->print_intrinsics() || C->print_inlining()) {
 405     if (jvms->has_method()) {
 406       // Not a root compile.
 407       const char* msg;
 408       if (callee->intrinsic_candidate()) {
 409         msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 410       } else {
 411         msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 412                            : "failed to inline (intrinsic), method not annotated";
 413       }
 414       C->print_inlining(callee, jvms->depth() - 1, bci, msg);
 415     } else {
 416       // Root compile
 417       tty->print("Did not generate intrinsic %s%s at bci:%d in",
 418                vmIntrinsics::name_at(intrinsic_id()),
 419                (is_virtual() ? " (virtual)" : ""), bci);
 420     }
 421   }
 422   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 423   C->print_inlining_update(this);
 424   return NULL;
 425 }
 426 
 427 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 428   LibraryCallKit kit(jvms, this);
 429   Compile* C = kit.C;
 430   int nodes = C->unique();
 431   _last_predicate = predicate;
 432 #ifndef PRODUCT
 433   assert(is_predicated() && predicate < predicates_count(), "sanity");
 434   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 435     char buf[1000];
 436     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 437     tty->print_cr("Predicate for intrinsic %s", str);
 438   }
 439 #endif
 440   ciMethod* callee = kit.callee();
 441   const int bci    = kit.bci();
 442 
 443   Node* slow_ctl = kit.try_to_predicate(predicate);
 444   if (!kit.failing()) {
 445     if (C->print_intrinsics() || C->print_inlining()) {
 446       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");
 447     }
 448     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 449     if (C->log()) {
 450       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 451                      vmIntrinsics::name_at(intrinsic_id()),
 452                      (is_virtual() ? " virtual='1'" : ""),
 453                      C->unique() - nodes);
 454     }
 455     return slow_ctl; // Could be NULL if the check folds.
 456   }
 457 
 458   // The intrinsic bailed out
 459   if (C->print_intrinsics() || C->print_inlining()) {
 460     if (jvms->has_method()) {
 461       // Not a root compile.
 462       const char* msg = "failed to generate predicate for intrinsic";
 463       C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
 464     } else {
 465       // Root compile
 466       C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
 467                                         vmIntrinsics::name_at(intrinsic_id()),
 468                                         (is_virtual() ? " (virtual)" : ""), bci);
 469     }
 470   }
 471   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 472   return NULL;
 473 }
 474 
 475 bool LibraryCallKit::try_to_inline(int predicate) {
 476   // Handle symbolic names for otherwise undistinguished boolean switches:
 477   const bool is_store       = true;
 478   const bool is_compress    = true;
 479   const bool is_native_ptr  = true;
 480   const bool is_static      = true;
 481   const bool is_volatile    = true;
 482 
 483   if (!jvms()->has_method()) {
 484     // Root JVMState has a null method.
 485     assert(map()->memory()->Opcode() == Op_Parm, "");
 486     // Insert the memory aliasing node
 487     set_all_memory(reset_memory());
 488   }
 489   assert(merged_memory(), "");
 490 
 491 
 492   switch (intrinsic_id()) {
 493   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 494   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 495   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 496 
 497   case vmIntrinsics::_dsin:
 498   case vmIntrinsics::_dcos:
 499   case vmIntrinsics::_dtan:
 500   case vmIntrinsics::_dabs:
 501   case vmIntrinsics::_datan2:
 502   case vmIntrinsics::_dsqrt:
 503   case vmIntrinsics::_dexp:
 504   case vmIntrinsics::_dlog:
 505   case vmIntrinsics::_dlog10:
 506   case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
 507 
 508   case vmIntrinsics::_min:
 509   case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
 510 
 511   case vmIntrinsics::_notify:
 512   case vmIntrinsics::_notifyAll:
 513     if (InlineNotify) {
 514       return inline_notify(intrinsic_id());
 515     }
 516     return false;
 517 
 518   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 519   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 520   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 521   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 522   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 523   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 524   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 525   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 526   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 527   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 528   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 529   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 530 
 531   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 532 
 533   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 534   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 535   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 536   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 537 
 538   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 539   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 540   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 541   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 542   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 543   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 544   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar();
 545 
 546   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 547   case vmIntrinsics::_equalsU:                  return inline_string_equals(StrIntrinsicNode::UU);
 548 
 549   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 550   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 551   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 552   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 553 
 554   case vmIntrinsics::_compressStringC:
 555   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 556   case vmIntrinsics::_inflateStringC:
 557   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 558 
 559   case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   Relaxed, false);
 560   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  Relaxed, false);
 561   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     Relaxed, false);
 562   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    Relaxed, false);
 563   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     Relaxed, false);
 564   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      Relaxed, false);
 565   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     Relaxed, false);
 566   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    Relaxed, false);
 567   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   Relaxed, false);
 568 
 569   case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   Relaxed, false);
 570   case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  Relaxed, false);
 571   case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     Relaxed, false);
 572   case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    Relaxed, false);
 573   case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     Relaxed, false);
 574   case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Relaxed, false);
 575   case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Relaxed, false);
 576   case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    Relaxed, false);
 577   case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   Relaxed, false);
 578 
 579   case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,     Relaxed, false);
 580   case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,    Relaxed, false);
 581   case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,     Relaxed, false);
 582   case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,      Relaxed, false);
 583   case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,     Relaxed, false);
 584   case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,    Relaxed, false);
 585   case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,   Relaxed, false);
 586   case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS,  Relaxed, false);
 587 
 588   case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,     Relaxed, false);
 589   case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,    Relaxed, false);
 590   case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,     Relaxed, false);
 591   case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,      Relaxed, false);
 592   case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,     Relaxed, false);
 593   case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,    Relaxed, false);
 594   case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,   Relaxed, false);
 595   case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS,  Relaxed, false);
 596 
 597   case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   Volatile, false);
 598   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  Volatile, false);
 599   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     Volatile, false);
 600   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    Volatile, false);
 601   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     Volatile, false);
 602   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      Volatile, false);
 603   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     Volatile, false);
 604   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    Volatile, false);
 605   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   Volatile, false);
 606 
 607   case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   Volatile, false);
 608   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  Volatile, false);
 609   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     Volatile, false);
 610   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    Volatile, false);
 611   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     Volatile, false);
 612   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Volatile, false);
 613   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Volatile, false);
 614   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    Volatile, false);
 615   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   Volatile, false);
 616 
 617   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    Relaxed, true);
 618   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     Relaxed, true);
 619   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      Relaxed, true);
 620   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     Relaxed, true);
 621 
 622   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    Relaxed, true);
 623   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     Relaxed, true);
 624   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Relaxed, true);
 625   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Relaxed, true);
 626 
 627   case vmIntrinsics::_putOrderedObject:         return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   Release, false);
 628   case vmIntrinsics::_putOrderedInt:            return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Release, false);
 629   case vmIntrinsics::_putOrderedLong:           return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Release, false);
 630 
 631   case vmIntrinsics::_getObjectAcquire:         return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   Acquire, false);
 632   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  Acquire, false);
 633   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     Acquire, false);
 634   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    Acquire, false);
 635   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     Acquire, false);
 636   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      Acquire, false);
 637   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     Acquire, false);
 638   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    Acquire, false);
 639   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   Acquire, false);
 640 
 641   case vmIntrinsics::_putObjectRelease:         return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   Release, false);
 642   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  Release, false);
 643   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     Release, false);
 644   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    Release, false);
 645   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     Release, false);
 646   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Release, false);
 647   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Release, false);
 648   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    Release, false);
 649   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   Release, false);
 650 
 651   case vmIntrinsics::_getObjectOpaque:          return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   Opaque, false);
 652   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  Opaque, false);
 653   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     Opaque, false);
 654   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    Opaque, false);
 655   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     Opaque, false);
 656   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      Opaque, false);
 657   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     Opaque, false);
 658   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    Opaque, false);
 659   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   Opaque, false);
 660 
 661   case vmIntrinsics::_putObjectOpaque:          return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   Opaque, false);
 662   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  Opaque, false);
 663   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     Opaque, false);
 664   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    Opaque, false);
 665   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     Opaque, false);
 666   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      Opaque, false);
 667   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     Opaque, false);
 668   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    Opaque, false);
 669   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   Opaque, false);
 670 
 671   case vmIntrinsics::_compareAndSwapObject:             return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 672   case vmIntrinsics::_compareAndSwapInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 673   case vmIntrinsics::_compareAndSwapLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 674 
 675   case vmIntrinsics::_weakCompareAndSwapObject:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 676   case vmIntrinsics::_weakCompareAndSwapObjectAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 677   case vmIntrinsics::_weakCompareAndSwapObjectRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 678   case vmIntrinsics::_weakCompareAndSwapInt:            return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 679   case vmIntrinsics::_weakCompareAndSwapIntAcquire:     return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 680   case vmIntrinsics::_weakCompareAndSwapIntRelease:     return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 681   case vmIntrinsics::_weakCompareAndSwapLong:           return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 682   case vmIntrinsics::_weakCompareAndSwapLongAcquire:    return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 683   case vmIntrinsics::_weakCompareAndSwapLongRelease:    return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 684 
 685   case vmIntrinsics::_compareAndExchangeObjectVolatile: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 686   case vmIntrinsics::_compareAndExchangeObjectAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 687   case vmIntrinsics::_compareAndExchangeObjectRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 688   case vmIntrinsics::_compareAndExchangeIntVolatile:    return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 689   case vmIntrinsics::_compareAndExchangeIntAcquire:     return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 690   case vmIntrinsics::_compareAndExchangeIntRelease:     return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 691   case vmIntrinsics::_compareAndExchangeLongVolatile:   return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 692   case vmIntrinsics::_compareAndExchangeLongAcquire:    return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 693   case vmIntrinsics::_compareAndExchangeLongRelease:    return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 694 
 695   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 696   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 697   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 698   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 699   case vmIntrinsics::_getAndSetObject:                  return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 700 
 701   case vmIntrinsics::_loadFence:
 702   case vmIntrinsics::_storeFence:
 703   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 704 
 705   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 706   case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
 707 
 708 #ifdef TRACE_HAVE_INTRINSICS
 709   case vmIntrinsics::_classID:                  return inline_native_classID();
 710   case vmIntrinsics::_threadID:                 return inline_native_threadID();
 711   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, TRACE_TIME_METHOD), "counterTime");
 712 #endif
 713   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 714   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 715   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 716   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 717   case vmIntrinsics::_newArray:                 return inline_native_newArray();
 718   case vmIntrinsics::_getLength:                return inline_native_getLength();
 719   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 720   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 721   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 722   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 723   case vmIntrinsics::_Objects_checkIndex:       return inline_objects_checkIndex();
 724   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 725 
 726   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 727 
 728   case vmIntrinsics::_isInstance:
 729   case vmIntrinsics::_getModifiers:
 730   case vmIntrinsics::_isInterface:
 731   case vmIntrinsics::_isArray:
 732   case vmIntrinsics::_isPrimitive:
 733   case vmIntrinsics::_getSuperclass:
 734   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 735 
 736   case vmIntrinsics::_floatToRawIntBits:
 737   case vmIntrinsics::_floatToIntBits:
 738   case vmIntrinsics::_intBitsToFloat:
 739   case vmIntrinsics::_doubleToRawLongBits:
 740   case vmIntrinsics::_doubleToLongBits:
 741   case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
 742 
 743   case vmIntrinsics::_numberOfLeadingZeros_i:
 744   case vmIntrinsics::_numberOfLeadingZeros_l:
 745   case vmIntrinsics::_numberOfTrailingZeros_i:
 746   case vmIntrinsics::_numberOfTrailingZeros_l:
 747   case vmIntrinsics::_bitCount_i:
 748   case vmIntrinsics::_bitCount_l:
 749   case vmIntrinsics::_reverseBytes_i:
 750   case vmIntrinsics::_reverseBytes_l:
 751   case vmIntrinsics::_reverseBytes_s:
 752   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 753 
 754   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 755 
 756   case vmIntrinsics::_Reference_get:            return inline_reference_get();
 757 
 758   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 759 
 760   case vmIntrinsics::_aescrypt_encryptBlock:
 761   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 762 
 763   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 764   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 765     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 766 
 767   case vmIntrinsics::_counterMode_AESCrypt:
 768     return inline_counterMode_AESCrypt(intrinsic_id());
 769 
 770   case vmIntrinsics::_sha_implCompress:
 771   case vmIntrinsics::_sha2_implCompress:
 772   case vmIntrinsics::_sha5_implCompress:
 773     return inline_sha_implCompress(intrinsic_id());
 774 
 775   case vmIntrinsics::_digestBase_implCompressMB:
 776     return inline_digestBase_implCompressMB(predicate);
 777 
 778   case vmIntrinsics::_multiplyToLen:
 779     return inline_multiplyToLen();
 780 
 781   case vmIntrinsics::_squareToLen:
 782     return inline_squareToLen();
 783 
 784   case vmIntrinsics::_mulAdd:
 785     return inline_mulAdd();
 786 
 787   case vmIntrinsics::_montgomeryMultiply:
 788     return inline_montgomeryMultiply();
 789   case vmIntrinsics::_montgomerySquare:
 790     return inline_montgomerySquare();
 791 
 792   case vmIntrinsics::_vectorizedMismatch:
 793     return inline_vectorizedMismatch();
 794 
 795   case vmIntrinsics::_ghash_processBlocks:
 796     return inline_ghash_processBlocks();
 797 
 798   case vmIntrinsics::_encodeISOArray:
 799   case vmIntrinsics::_encodeByteISOArray:
 800     return inline_encodeISOArray();
 801 
 802   case vmIntrinsics::_updateCRC32:
 803     return inline_updateCRC32();
 804   case vmIntrinsics::_updateBytesCRC32:
 805     return inline_updateBytesCRC32();
 806   case vmIntrinsics::_updateByteBufferCRC32:
 807     return inline_updateByteBufferCRC32();
 808 
 809   case vmIntrinsics::_updateBytesCRC32C:
 810     return inline_updateBytesCRC32C();
 811   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 812     return inline_updateDirectByteBufferCRC32C();
 813 
 814   case vmIntrinsics::_updateBytesAdler32:
 815     return inline_updateBytesAdler32();
 816   case vmIntrinsics::_updateByteBufferAdler32:
 817     return inline_updateByteBufferAdler32();
 818 
 819   case vmIntrinsics::_profileBoolean:
 820     return inline_profileBoolean();
 821   case vmIntrinsics::_isCompileConstant:
 822     return inline_isCompileConstant();
 823 
 824   case vmIntrinsics::_hasNegatives:
 825     return inline_hasNegatives();
 826 
 827   case vmIntrinsics::_deoptimize:
 828     return inline_deoptimize();
 829 
 830   default:
 831     // If you get here, it may be that someone has added a new intrinsic
 832     // to the list in vmSymbols.hpp without implementing it here.
 833 #ifndef PRODUCT
 834     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 835       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 836                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
 837     }
 838 #endif
 839     return false;
 840   }
 841 }
 842 
 843 Node* LibraryCallKit::try_to_predicate(int predicate) {
 844   if (!jvms()->has_method()) {
 845     // Root JVMState has a null method.
 846     assert(map()->memory()->Opcode() == Op_Parm, "");
 847     // Insert the memory aliasing node
 848     set_all_memory(reset_memory());
 849   }
 850   assert(merged_memory(), "");
 851 
 852   switch (intrinsic_id()) {
 853   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 854     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 855   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 856     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 857   case vmIntrinsics::_counterMode_AESCrypt:
 858     return inline_counterMode_AESCrypt_predicate();
 859   case vmIntrinsics::_digestBase_implCompressMB:
 860     return inline_digestBase_implCompressMB_predicate(predicate);
 861 
 862   default:
 863     // If you get here, it may be that someone has added a new intrinsic
 864     // to the list in vmSymbols.hpp without implementing it here.
 865 #ifndef PRODUCT
 866     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 867       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 868                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
 869     }
 870 #endif
 871     Node* slow_ctl = control();
 872     set_control(top()); // No fast path instrinsic
 873     return slow_ctl;
 874   }
 875 }
 876 
 877 //------------------------------set_result-------------------------------
 878 // Helper function for finishing intrinsics.
 879 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 880   record_for_igvn(region);
 881   set_control(_gvn.transform(region));
 882   set_result( _gvn.transform(value));
 883   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 884 }
 885 
 886 //------------------------------generate_guard---------------------------
 887 // Helper function for generating guarded fast-slow graph structures.
 888 // The given 'test', if true, guards a slow path.  If the test fails
 889 // then a fast path can be taken.  (We generally hope it fails.)
 890 // In all cases, GraphKit::control() is updated to the fast path.
 891 // The returned value represents the control for the slow path.
 892 // The return value is never 'top'; it is either a valid control
 893 // or NULL if it is obvious that the slow path can never be taken.
 894 // Also, if region and the slow control are not NULL, the slow edge
 895 // is appended to the region.
 896 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 897   if (stopped()) {
 898     // Already short circuited.
 899     return NULL;
 900   }
 901 
 902   // Build an if node and its projections.
 903   // If test is true we take the slow path, which we assume is uncommon.
 904   if (_gvn.type(test) == TypeInt::ZERO) {
 905     // The slow branch is never taken.  No need to build this guard.
 906     return NULL;
 907   }
 908 
 909   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 910 
 911   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 912   if (if_slow == top()) {
 913     // The slow branch is never taken.  No need to build this guard.
 914     return NULL;
 915   }
 916 
 917   if (region != NULL)
 918     region->add_req(if_slow);
 919 
 920   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 921   set_control(if_fast);
 922 
 923   return if_slow;
 924 }
 925 
 926 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 927   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 928 }
 929 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 930   return generate_guard(test, region, PROB_FAIR);
 931 }
 932 
 933 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 934                                                      Node* *pos_index) {
 935   if (stopped())
 936     return NULL;                // already stopped
 937   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 938     return NULL;                // index is already adequately typed
 939   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 940   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 941   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 942   if (is_neg != NULL && pos_index != NULL) {
 943     // Emulate effect of Parse::adjust_map_after_if.
 944     Node* ccast = new CastIINode(index, TypeInt::POS);
 945     ccast->set_req(0, control());
 946     (*pos_index) = _gvn.transform(ccast);
 947   }
 948   return is_neg;
 949 }
 950 
 951 // Make sure that 'position' is a valid limit index, in [0..length].
 952 // There are two equivalent plans for checking this:
 953 //   A. (offset + copyLength)  unsigned<=  arrayLength
 954 //   B. offset  <=  (arrayLength - copyLength)
 955 // We require that all of the values above, except for the sum and
 956 // difference, are already known to be non-negative.
 957 // Plan A is robust in the face of overflow, if offset and copyLength
 958 // are both hugely positive.
 959 //
 960 // Plan B is less direct and intuitive, but it does not overflow at
 961 // all, since the difference of two non-negatives is always
 962 // representable.  Whenever Java methods must perform the equivalent
 963 // check they generally use Plan B instead of Plan A.
 964 // For the moment we use Plan A.
 965 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 966                                                   Node* subseq_length,
 967                                                   Node* array_length,
 968                                                   RegionNode* region) {
 969   if (stopped())
 970     return NULL;                // already stopped
 971   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 972   if (zero_offset && subseq_length->eqv_uncast(array_length))
 973     return NULL;                // common case of whole-array copy
 974   Node* last = subseq_length;
 975   if (!zero_offset)             // last += offset
 976     last = _gvn.transform(new AddINode(last, offset));
 977   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 978   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 979   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 980   return is_over;
 981 }
 982 
 983 // Emit range checks for the given String.value byte array
 984 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 985   if (stopped()) {
 986     return; // already stopped
 987   }
 988   RegionNode* bailout = new RegionNode(1);
 989   record_for_igvn(bailout);
 990   if (char_count) {
 991     // Convert char count to byte count
 992     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 993   }
 994 
 995   // Offset and count must not be negative
 996   generate_negative_guard(offset, bailout);
 997   generate_negative_guard(count, bailout);
 998   // Offset + count must not exceed length of array
 999   generate_limit_guard(offset, count, load_array_length(array), bailout);
1000 
1001   if (bailout->req() > 1) {
1002     PreserveJVMState pjvms(this);
1003     set_control(_gvn.transform(bailout));
1004     uncommon_trap(Deoptimization::Reason_intrinsic,
1005                   Deoptimization::Action_maybe_recompile);
1006   }
1007 }
1008 
1009 //--------------------------generate_current_thread--------------------
1010 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1011   ciKlass*    thread_klass = env()->Thread_klass();
1012   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1013   Node* thread = _gvn.transform(new ThreadLocalNode());
1014   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
1015   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);
1016   tls_output = thread;
1017   return threadObj;
1018 }
1019 
1020 
1021 //------------------------------make_string_method_node------------------------
1022 // Helper method for String intrinsic functions. This version is called with
1023 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1024 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1025 // containing the lengths of str1 and str2.
1026 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1027   Node* result = NULL;
1028   switch (opcode) {
1029   case Op_StrIndexOf:
1030     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1031                                 str1_start, cnt1, str2_start, cnt2, ae);
1032     break;
1033   case Op_StrComp:
1034     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1035                              str1_start, cnt1, str2_start, cnt2, ae);
1036     break;
1037   case Op_StrEquals:
1038     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1039     // Use the constant length if there is one because optimized match rule may exist.
1040     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1041                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1042     break;
1043   default:
1044     ShouldNotReachHere();
1045     return NULL;
1046   }
1047 
1048   // All these intrinsics have checks.
1049   C->set_has_split_ifs(true); // Has chance for split-if optimization
1050 
1051   return _gvn.transform(result);
1052 }
1053 
1054 //------------------------------inline_string_compareTo------------------------
1055 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1056   Node* arg1 = argument(0);
1057   Node* arg2 = argument(1);
1058 
1059   // Get start addr and length of first argument
1060   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1061   Node* arg1_cnt    = load_array_length(arg1);
1062 
1063   // Get start addr and length of second argument
1064   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1065   Node* arg2_cnt    = load_array_length(arg2);
1066 
1067   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1068   set_result(result);
1069   return true;
1070 }
1071 
1072 //------------------------------inline_string_equals------------------------
1073 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1074   Node* arg1 = argument(0);
1075   Node* arg2 = argument(1);
1076 
1077   // paths (plus control) merge
1078   RegionNode* region = new RegionNode(3);
1079   Node* phi = new PhiNode(region, TypeInt::BOOL);
1080 
1081   if (!stopped()) {
1082     // Get start addr and length of first argument
1083     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1084     Node* arg1_cnt    = load_array_length(arg1);
1085 
1086     // Get start addr and length of second argument
1087     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1088     Node* arg2_cnt    = load_array_length(arg2);
1089 
1090     // Check for arg1_cnt != arg2_cnt
1091     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1092     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1093     Node* if_ne = generate_slow_guard(bol, NULL);
1094     if (if_ne != NULL) {
1095       phi->init_req(2, intcon(0));
1096       region->init_req(2, if_ne);
1097     }
1098 
1099     // Check for count == 0 is done by assembler code for StrEquals.
1100 
1101     if (!stopped()) {
1102       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1103       phi->init_req(1, equals);
1104       region->init_req(1, control());
1105     }
1106   }
1107 
1108   // post merge
1109   set_control(_gvn.transform(region));
1110   record_for_igvn(region);
1111 
1112   set_result(_gvn.transform(phi));
1113   return true;
1114 }
1115 
1116 //------------------------------inline_array_equals----------------------------
1117 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1118   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1119   Node* arg1 = argument(0);
1120   Node* arg2 = argument(1);
1121 
1122   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1123   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1124   return true;
1125 }
1126 
1127 //------------------------------inline_hasNegatives------------------------------
1128 bool LibraryCallKit::inline_hasNegatives() {
1129   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1130     return false;
1131   }
1132 
1133   assert(callee()->signature()->size() == 3, "hasNegatives has 3 parameters");
1134   // no receiver since it is static method
1135   Node* ba         = argument(0);
1136   Node* offset     = argument(1);
1137   Node* len        = argument(2);
1138 
1139   // Range checks
1140   generate_string_range_check(ba, offset, len, false);
1141   if (stopped()) {
1142     return true;
1143   }
1144   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1145   Node* result = new HasNegativesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1146   set_result(_gvn.transform(result));
1147   return true;
1148 }
1149 
1150 bool LibraryCallKit::inline_objects_checkIndex() {
1151   Node* index = argument(0);
1152   Node* length = argument(1);
1153   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1154     return false;
1155   }
1156 
1157   Node* len_pos_cmp = _gvn.transform(new CmpINode(length, intcon(0)));
1158   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1159 
1160   {
1161     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1162     uncommon_trap(Deoptimization::Reason_intrinsic,
1163                   Deoptimization::Action_make_not_entrant);
1164   }
1165 
1166   if (stopped()) {
1167     return false;
1168   }
1169 
1170   Node* rc_cmp = _gvn.transform(new CmpUNode(index, length));
1171   BoolTest::mask btest = BoolTest::lt;
1172   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1173   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1174   _gvn.set_type(rc, rc->Value(&_gvn));
1175   if (!rc_bool->is_Con()) {
1176     record_for_igvn(rc);
1177   }
1178   set_control(_gvn.transform(new IfTrueNode(rc)));
1179   {
1180     PreserveJVMState pjvms(this);
1181     set_control(_gvn.transform(new IfFalseNode(rc)));
1182     uncommon_trap(Deoptimization::Reason_range_check,
1183                   Deoptimization::Action_make_not_entrant);
1184   }
1185 
1186   if (stopped()) {
1187     return false;
1188   }
1189 
1190   Node* result = new CastIINode(index, TypeInt::make(0, _gvn.type(length)->is_int()->_hi, Type::WidenMax));
1191   result->set_req(0, control());
1192   result = _gvn.transform(result);
1193   set_result(result);
1194   replace_in_map(index, result);
1195   return true;
1196 }
1197 
1198 //------------------------------inline_string_indexOf------------------------
1199 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1200   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1201     return false;
1202   }
1203   Node* src = argument(0);
1204   Node* tgt = argument(1);
1205 
1206   // Make the merge point
1207   RegionNode* result_rgn = new RegionNode(4);
1208   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1209 
1210   // Get start addr and length of source string
1211   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1212   Node* src_count = load_array_length(src);
1213 
1214   // Get start addr and length of substring
1215   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1216   Node* tgt_count = load_array_length(tgt);
1217 
1218   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1219     // Divide src size by 2 if String is UTF16 encoded
1220     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1221   }
1222   if (ae == StrIntrinsicNode::UU) {
1223     // Divide substring size by 2 if String is UTF16 encoded
1224     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1225   }
1226 
1227   Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, result_rgn, result_phi, ae);
1228   if (result != NULL) {
1229     result_phi->init_req(3, result);
1230     result_rgn->init_req(3, control());
1231   }
1232   set_control(_gvn.transform(result_rgn));
1233   record_for_igvn(result_rgn);
1234   set_result(_gvn.transform(result_phi));
1235 
1236   return true;
1237 }
1238 
1239 //-----------------------------inline_string_indexOf-----------------------
1240 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1241   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1242     return false;
1243   }
1244   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1245     return false;
1246   }
1247   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1248   Node* src         = argument(0); // byte[]
1249   Node* src_count   = argument(1); // char count
1250   Node* tgt         = argument(2); // byte[]
1251   Node* tgt_count   = argument(3); // char count
1252   Node* from_index  = argument(4); // char index
1253 
1254   // Multiply byte array index by 2 if String is UTF16 encoded
1255   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1256   src_count = _gvn.transform(new SubINode(src_count, from_index));
1257   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1258   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1259 
1260   // Range checks
1261   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1262   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1263   if (stopped()) {
1264     return true;
1265   }
1266 
1267   RegionNode* region = new RegionNode(5);
1268   Node* phi = new PhiNode(region, TypeInt::INT);
1269 
1270   Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, region, phi, ae);
1271   if (result != NULL) {
1272     // The result is index relative to from_index if substring was found, -1 otherwise.
1273     // Generate code which will fold into cmove.
1274     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1275     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1276 
1277     Node* if_lt = generate_slow_guard(bol, NULL);
1278     if (if_lt != NULL) {
1279       // result == -1
1280       phi->init_req(3, result);
1281       region->init_req(3, if_lt);
1282     }
1283     if (!stopped()) {
1284       result = _gvn.transform(new AddINode(result, from_index));
1285       phi->init_req(4, result);
1286       region->init_req(4, control());
1287     }
1288   }
1289 
1290   set_control(_gvn.transform(region));
1291   record_for_igvn(region);
1292   set_result(_gvn.transform(phi));
1293 
1294   return true;
1295 }
1296 
1297 // Create StrIndexOfNode with fast path checks
1298 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1299                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1300   // Check for substr count > string count
1301   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1302   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1303   Node* if_gt = generate_slow_guard(bol, NULL);
1304   if (if_gt != NULL) {
1305     phi->init_req(1, intcon(-1));
1306     region->init_req(1, if_gt);
1307   }
1308   if (!stopped()) {
1309     // Check for substr count == 0
1310     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1311     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1312     Node* if_zero = generate_slow_guard(bol, NULL);
1313     if (if_zero != NULL) {
1314       phi->init_req(2, intcon(0));
1315       region->init_req(2, if_zero);
1316     }
1317   }
1318   if (!stopped()) {
1319     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1320   }
1321   return NULL;
1322 }
1323 
1324 //-----------------------------inline_string_indexOfChar-----------------------
1325 bool LibraryCallKit::inline_string_indexOfChar() {
1326   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1327     return false;
1328   }
1329   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1330     return false;
1331   }
1332   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1333   Node* src         = argument(0); // byte[]
1334   Node* tgt         = argument(1); // tgt is int ch
1335   Node* from_index  = argument(2);
1336   Node* max         = argument(3);
1337 
1338   Node* src_offset = _gvn.transform(new LShiftINode(from_index, intcon(1)));
1339   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1340   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1341 
1342   // Range checks
1343   generate_string_range_check(src, src_offset, src_count, true);
1344   if (stopped()) {
1345     return true;
1346   }
1347 
1348   RegionNode* region = new RegionNode(3);
1349   Node* phi = new PhiNode(region, TypeInt::INT);
1350 
1351   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, tgt, StrIntrinsicNode::none);
1352   C->set_has_split_ifs(true); // Has chance for split-if optimization
1353   _gvn.transform(result);
1354 
1355   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1356   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1357 
1358   Node* if_lt = generate_slow_guard(bol, NULL);
1359   if (if_lt != NULL) {
1360     // result == -1
1361     phi->init_req(2, result);
1362     region->init_req(2, if_lt);
1363   }
1364   if (!stopped()) {
1365     result = _gvn.transform(new AddINode(result, from_index));
1366     phi->init_req(1, result);
1367     region->init_req(1, control());
1368   }
1369   set_control(_gvn.transform(region));
1370   record_for_igvn(region);
1371   set_result(_gvn.transform(phi));
1372 
1373   return true;
1374 }
1375 //---------------------------inline_string_copy---------------------
1376 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1377 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1378 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1379 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1380 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1381 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1382 bool LibraryCallKit::inline_string_copy(bool compress) {
1383   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1384     return false;
1385   }
1386   int nargs = 5;  // 2 oops, 3 ints
1387   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1388 
1389   Node* src         = argument(0);
1390   Node* src_offset  = argument(1);
1391   Node* dst         = argument(2);
1392   Node* dst_offset  = argument(3);
1393   Node* length      = argument(4);
1394 
1395   // Check for allocation before we add nodes that would confuse
1396   // tightly_coupled_allocation()
1397   AllocateArrayNode* alloc = tightly_coupled_allocation(dst, NULL);
1398 
1399   // Figure out the size and type of the elements we will be copying.
1400   const Type* src_type = src->Value(&_gvn);
1401   const Type* dst_type = dst->Value(&_gvn);
1402   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1403   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1404   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1405          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1406          "Unsupported array types for inline_string_copy");
1407 
1408   // Range checks
1409   generate_string_range_check(src, src_offset, length, compress && src_elem == T_BYTE);
1410   generate_string_range_check(dst, dst_offset, length, !compress && dst_elem == T_BYTE);
1411   if (stopped()) {
1412     return true;
1413   }
1414 
1415   // Convert char[] offsets to byte[] offsets
1416   if (compress && src_elem == T_BYTE) {
1417     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1418   } else if (!compress && dst_elem == T_BYTE) {
1419     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1420   }
1421 
1422   Node* src_start = array_element_address(src, src_offset, src_elem);
1423   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1424   // 'src_start' points to src array + scaled offset
1425   // 'dst_start' points to dst array + scaled offset
1426   Node* count = NULL;
1427   if (compress) {
1428     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1429   } else {
1430     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1431   }
1432 
1433   if (alloc != NULL) {
1434     if (alloc->maybe_set_complete(&_gvn)) {
1435       // "You break it, you buy it."
1436       InitializeNode* init = alloc->initialization();
1437       assert(init->is_complete(), "we just did this");
1438       init->set_complete_with_arraycopy();
1439       assert(dst->is_CheckCastPP(), "sanity");
1440       assert(dst->in(0)->in(0) == init, "dest pinned");
1441     }
1442     // Do not let stores that initialize this object be reordered with
1443     // a subsequent store that would make this object accessible by
1444     // other threads.
1445     // Record what AllocateNode this StoreStore protects so that
1446     // escape analysis can go from the MemBarStoreStoreNode to the
1447     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1448     // based on the escape status of the AllocateNode.
1449     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
1450   }
1451   if (compress) {
1452     set_result(_gvn.transform(count));
1453   }
1454   return true;
1455 }
1456 
1457 #ifdef _LP64
1458 #define XTOP ,top() /*additional argument*/
1459 #else  //_LP64
1460 #define XTOP        /*no additional argument*/
1461 #endif //_LP64
1462 
1463 //------------------------inline_string_toBytesU--------------------------
1464 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1465 bool LibraryCallKit::inline_string_toBytesU() {
1466   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1467     return false;
1468   }
1469   // Get the arguments.
1470   Node* value     = argument(0);
1471   Node* offset    = argument(1);
1472   Node* length    = argument(2);
1473 
1474   Node* newcopy = NULL;
1475 
1476   // Set the original stack and the reexecute bit for the interpreter to reexecute
1477   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1478   { PreserveReexecuteState preexecs(this);
1479     jvms()->set_should_reexecute(true);
1480 
1481     // Check if a null path was taken unconditionally.
1482     value = null_check(value);
1483 
1484     RegionNode* bailout = new RegionNode(1);
1485     record_for_igvn(bailout);
1486 
1487     // Range checks
1488     generate_negative_guard(offset, bailout);
1489     generate_negative_guard(length, bailout);
1490     generate_limit_guard(offset, length, load_array_length(value), bailout);
1491     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1492     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1493 
1494     if (bailout->req() > 1) {
1495       PreserveJVMState pjvms(this);
1496       set_control(_gvn.transform(bailout));
1497       uncommon_trap(Deoptimization::Reason_intrinsic,
1498                     Deoptimization::Action_maybe_recompile);
1499     }
1500     if (stopped()) {
1501       return true;
1502     }
1503 
1504     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1505     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1506     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1507     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy, NULL);
1508 
1509     // Calculate starting addresses.
1510     Node* src_start = array_element_address(value, offset, T_CHAR);
1511     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1512 
1513     // Check if src array address is aligned to HeapWordSize (dst is always aligned)
1514     const TypeInt* toffset = gvn().type(offset)->is_int();
1515     bool aligned = toffset->is_con() && ((toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1516 
1517     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1518     const char* copyfunc_name = "arraycopy";
1519     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1520     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1521                       OptoRuntime::fast_arraycopy_Type(),
1522                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1523                       src_start, dst_start, ConvI2X(length) XTOP);
1524     // Do not let reads from the cloned object float above the arraycopy.
1525     if (alloc != NULL) {
1526       if (alloc->maybe_set_complete(&_gvn)) {
1527         // "You break it, you buy it."
1528         InitializeNode* init = alloc->initialization();
1529         assert(init->is_complete(), "we just did this");
1530         init->set_complete_with_arraycopy();
1531         assert(newcopy->is_CheckCastPP(), "sanity");
1532         assert(newcopy->in(0)->in(0) == init, "dest pinned");
1533       }
1534       // Do not let stores that initialize this object be reordered with
1535       // a subsequent store that would make this object accessible by
1536       // other threads.
1537       // Record what AllocateNode this StoreStore protects so that
1538       // escape analysis can go from the MemBarStoreStoreNode to the
1539       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1540       // based on the escape status of the AllocateNode.
1541       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
1542     } else {
1543       insert_mem_bar(Op_MemBarCPUOrder);
1544     }
1545   } // original reexecute is set back here
1546 
1547   C->set_has_split_ifs(true); // Has chance for split-if optimization
1548   if (!stopped()) {
1549     set_result(newcopy);
1550   }
1551   return true;
1552 }
1553 
1554 //------------------------inline_string_getCharsU--------------------------
1555 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1556 bool LibraryCallKit::inline_string_getCharsU() {
1557   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1558     return false;
1559   }
1560 
1561   // Get the arguments.
1562   Node* src       = argument(0);
1563   Node* src_begin = argument(1);
1564   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1565   Node* dst       = argument(3);
1566   Node* dst_begin = argument(4);
1567 
1568   // Check for allocation before we add nodes that would confuse
1569   // tightly_coupled_allocation()
1570   AllocateArrayNode* alloc = tightly_coupled_allocation(dst, NULL);
1571 
1572   // Check if a null path was taken unconditionally.
1573   src = null_check(src);
1574   dst = null_check(dst);
1575   if (stopped()) {
1576     return true;
1577   }
1578 
1579   // Get length and convert char[] offset to byte[] offset
1580   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1581   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1582 
1583   // Range checks
1584   generate_string_range_check(src, src_begin, length, true);
1585   generate_string_range_check(dst, dst_begin, length, false);
1586   if (stopped()) {
1587     return true;
1588   }
1589 
1590   if (!stopped()) {
1591     // Calculate starting addresses.
1592     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1593     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1594 
1595     // Check if array addresses are aligned to HeapWordSize
1596     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1597     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1598     bool aligned = tsrc->is_con() && ((tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1599                    tdst->is_con() && ((tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1600 
1601     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1602     const char* copyfunc_name = "arraycopy";
1603     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1604     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1605                       OptoRuntime::fast_arraycopy_Type(),
1606                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1607                       src_start, dst_start, ConvI2X(length) XTOP);
1608     // Do not let reads from the cloned object float above the arraycopy.
1609     if (alloc != NULL) {
1610       if (alloc->maybe_set_complete(&_gvn)) {
1611         // "You break it, you buy it."
1612         InitializeNode* init = alloc->initialization();
1613         assert(init->is_complete(), "we just did this");
1614         init->set_complete_with_arraycopy();
1615         assert(dst->is_CheckCastPP(), "sanity");
1616         assert(dst->in(0)->in(0) == init, "dest pinned");
1617       }
1618       // Do not let stores that initialize this object be reordered with
1619       // a subsequent store that would make this object accessible by
1620       // other threads.
1621       // Record what AllocateNode this StoreStore protects so that
1622       // escape analysis can go from the MemBarStoreStoreNode to the
1623       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1624       // based on the escape status of the AllocateNode.
1625       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
1626     } else {
1627       insert_mem_bar(Op_MemBarCPUOrder);
1628     }
1629   }
1630 
1631   C->set_has_split_ifs(true); // Has chance for split-if optimization
1632   return true;
1633 }
1634 
1635 //----------------------inline_string_char_access----------------------------
1636 // Store/Load char to/from byte[] array.
1637 // static void StringUTF16.putChar(byte[] val, int index, int c)
1638 // static char StringUTF16.getChar(byte[] val, int index)
1639 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1640   Node* value  = argument(0);
1641   Node* index  = argument(1);
1642   Node* ch = is_store ? argument(2) : NULL;
1643 
1644   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1645   // correctly requires matched array shapes.
1646   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1647           "sanity: byte[] and char[] bases agree");
1648   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1649           "sanity: byte[] and char[] scales agree");
1650 
1651   // Bail when getChar over constants is requested: constant folding would
1652   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1653   // Java method would constant fold nicely instead.
1654   if (!is_store && value->is_Con() && index->is_Con()) {
1655     return false;
1656   }
1657 
1658   Node* adr = array_element_address(value, index, T_CHAR);
1659   if (is_store) {
1660     (void) store_to_memory(control(), adr, ch, T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
1661                            false, false, true /* mismatched */);
1662   } else {
1663     ch = make_load(control(), adr, TypeInt::CHAR, T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
1664                    LoadNode::DependsOnlyOnTest, false, false, true /* mismatched */);
1665     set_result(ch);
1666   }
1667   return true;
1668 }
1669 
1670 //--------------------------round_double_node--------------------------------
1671 // Round a double node if necessary.
1672 Node* LibraryCallKit::round_double_node(Node* n) {
1673   if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
1674     n = _gvn.transform(new RoundDoubleNode(0, n));
1675   return n;
1676 }
1677 
1678 //------------------------------inline_math-----------------------------------
1679 // public static double Math.abs(double)
1680 // public static double Math.sqrt(double)
1681 // public static double Math.log(double)
1682 // public static double Math.log10(double)
1683 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1684   Node* arg = round_double_node(argument(0));
1685   Node* n = NULL;
1686   switch (id) {
1687   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1688   case vmIntrinsics::_dsqrt:  n = new SqrtDNode(C, control(),  arg);  break;
1689   case vmIntrinsics::_dlog10: n = new Log10DNode(C, control(), arg);  break;
1690   default:  fatal_unexpected_iid(id);  break;
1691   }
1692   set_result(_gvn.transform(n));
1693   return true;
1694 }
1695 
1696 //------------------------------inline_trig----------------------------------
1697 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1698 // argument reduction which will turn into a fast/slow diamond.
1699 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1700   Node* arg = round_double_node(argument(0));
1701   Node* n = NULL;
1702 
1703   switch (id) {
1704   case vmIntrinsics::_dtan:  n = new TanDNode(C, control(), arg);  break;
1705   default:  fatal_unexpected_iid(id);  break;
1706   }
1707   n = _gvn.transform(n);
1708 
1709   // Rounding required?  Check for argument reduction!
1710   if (Matcher::strict_fp_requires_explicit_rounding) {
1711     static const double     pi_4 =  0.7853981633974483;
1712     static const double neg_pi_4 = -0.7853981633974483;
1713     // pi/2 in 80-bit extended precision
1714     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1715     // -pi/2 in 80-bit extended precision
1716     // static const unsigned char neg_pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0xbf,0x00,0x00,0x00,0x00,0x00,0x00};
1717     // Cutoff value for using this argument reduction technique
1718     //static const double    pi_2_minus_epsilon =  1.564660403643354;
1719     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1720 
1721     // Pseudocode for sin:
1722     // if (x <= Math.PI / 4.0) {
1723     //   if (x >= -Math.PI / 4.0) return  fsin(x);
1724     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1725     // } else {
1726     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1727     // }
1728     // return StrictMath.sin(x);
1729 
1730     // Pseudocode for cos:
1731     // if (x <= Math.PI / 4.0) {
1732     //   if (x >= -Math.PI / 4.0) return  fcos(x);
1733     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1734     // } else {
1735     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1736     // }
1737     // return StrictMath.cos(x);
1738 
1739     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1740     // requires a special machine instruction to load it.  Instead we'll try
1741     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1742     // probably do the math inside the SIN encoding.
1743 
1744     // Make the merge point
1745     RegionNode* r = new RegionNode(3);
1746     Node* phi = new PhiNode(r, Type::DOUBLE);
1747 
1748     // Flatten arg so we need only 1 test
1749     Node *abs = _gvn.transform(new AbsDNode(arg));
1750     // Node for PI/4 constant
1751     Node *pi4 = makecon(TypeD::make(pi_4));
1752     // Check PI/4 : abs(arg)
1753     Node *cmp = _gvn.transform(new CmpDNode(pi4,abs));
1754     // Check: If PI/4 < abs(arg) then go slow
1755     Node *bol = _gvn.transform(new BoolNode( cmp, BoolTest::lt ));
1756     // Branch either way
1757     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1758     set_control(opt_iff(r,iff));
1759 
1760     // Set fast path result
1761     phi->init_req(2, n);
1762 
1763     // Slow path - non-blocking leaf call
1764     Node* call = NULL;
1765     switch (id) {
1766     case vmIntrinsics::_dtan:
1767       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1768                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1769                                "Tan", NULL, arg, top());
1770       break;
1771     }
1772     assert(control()->in(0) == call, "");
1773     Node* slow_result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1774     r->init_req(1, control());
1775     phi->init_req(1, slow_result);
1776 
1777     // Post-merge
1778     set_control(_gvn.transform(r));
1779     record_for_igvn(r);
1780     n = _gvn.transform(phi);
1781 
1782     C->set_has_split_ifs(true); // Has chance for split-if optimization
1783   }
1784   set_result(n);
1785   return true;
1786 }
1787 
1788 //------------------------------runtime_math-----------------------------
1789 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1790   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1791          "must be (DD)D or (D)D type");
1792 
1793   // Inputs
1794   Node* a = round_double_node(argument(0));
1795   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
1796 
1797   const TypePtr* no_memory_effects = NULL;
1798   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1799                                  no_memory_effects,
1800                                  a, top(), b, b ? top() : NULL);
1801   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1802 #ifdef ASSERT
1803   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1804   assert(value_top == top(), "second value must be top");
1805 #endif
1806 
1807   set_result(value);
1808   return true;
1809 }
1810 
1811 //------------------------------inline_math_native-----------------------------
1812 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1813 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
1814   switch (id) {
1815     // These intrinsics are not properly supported on all hardware
1816   case vmIntrinsics::_dsin:
1817     return StubRoutines::dsin() != NULL ?
1818       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1819       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
1820   case vmIntrinsics::_dcos:
1821     return StubRoutines::dcos() != NULL ?
1822       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1823       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
1824   case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
1825     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
1826 
1827   case vmIntrinsics::_dlog:
1828     return StubRoutines::dlog() != NULL ?
1829       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1830       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
1831   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
1832     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
1833 
1834     // These intrinsics are supported on all hardware
1835   case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;
1836   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
1837 
1838   case vmIntrinsics::_dexp:
1839     return StubRoutines::dexp() != NULL ?
1840       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1841       runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dexp),  "EXP");
1842   case vmIntrinsics::_dpow:
1843     return StubRoutines::dpow() != NULL ?
1844       runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(), "dpow") :
1845       runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
1846 #undef FN_PTR
1847 
1848    // These intrinsics are not yet correctly implemented
1849   case vmIntrinsics::_datan2:
1850     return false;
1851 
1852   default:
1853     fatal_unexpected_iid(id);
1854     return false;
1855   }
1856 }
1857 
1858 static bool is_simple_name(Node* n) {
1859   return (n->req() == 1         // constant
1860           || (n->is_Type() && n->as_Type()->type()->singleton())
1861           || n->is_Proj()       // parameter or return value
1862           || n->is_Phi()        // local of some sort
1863           );
1864 }
1865 
1866 //----------------------------inline_notify-----------------------------------*
1867 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1868   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1869   address func;
1870   if (id == vmIntrinsics::_notify) {
1871     func = OptoRuntime::monitor_notify_Java();
1872   } else {
1873     func = OptoRuntime::monitor_notifyAll_Java();
1874   }
1875   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, NULL, TypeRawPtr::BOTTOM, argument(0));
1876   make_slow_call_ex(call, env()->Throwable_klass(), false);
1877   return true;
1878 }
1879 
1880 
1881 //----------------------------inline_min_max-----------------------------------
1882 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1883   set_result(generate_min_max(id, argument(0), argument(1)));
1884   return true;
1885 }
1886 
1887 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
1888   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
1889   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
1890   Node* fast_path = _gvn.transform( new IfFalseNode(check));
1891   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
1892 
1893   {
1894     PreserveJVMState pjvms(this);
1895     PreserveReexecuteState preexecs(this);
1896     jvms()->set_should_reexecute(true);
1897 
1898     set_control(slow_path);
1899     set_i_o(i_o());
1900 
1901     uncommon_trap(Deoptimization::Reason_intrinsic,
1902                   Deoptimization::Action_none);
1903   }
1904 
1905   set_control(fast_path);
1906   set_result(math);
1907 }
1908 
1909 template <typename OverflowOp>
1910 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
1911   typedef typename OverflowOp::MathOp MathOp;
1912 
1913   MathOp* mathOp = new MathOp(arg1, arg2);
1914   Node* operation = _gvn.transform( mathOp );
1915   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
1916   inline_math_mathExact(operation, ofcheck);
1917   return true;
1918 }
1919 
1920 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
1921   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
1922 }
1923 
1924 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
1925   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
1926 }
1927 
1928 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
1929   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
1930 }
1931 
1932 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
1933   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
1934 }
1935 
1936 bool LibraryCallKit::inline_math_negateExactI() {
1937   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
1938 }
1939 
1940 bool LibraryCallKit::inline_math_negateExactL() {
1941   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
1942 }
1943 
1944 bool LibraryCallKit::inline_math_multiplyExactI() {
1945   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
1946 }
1947 
1948 bool LibraryCallKit::inline_math_multiplyExactL() {
1949   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
1950 }
1951 
1952 Node*
1953 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1954   // These are the candidate return value:
1955   Node* xvalue = x0;
1956   Node* yvalue = y0;
1957 
1958   if (xvalue == yvalue) {
1959     return xvalue;
1960   }
1961 
1962   bool want_max = (id == vmIntrinsics::_max);
1963 
1964   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1965   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1966   if (txvalue == NULL || tyvalue == NULL)  return top();
1967   // This is not really necessary, but it is consistent with a
1968   // hypothetical MaxINode::Value method:
1969   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1970 
1971   // %%% This folding logic should (ideally) be in a different place.
1972   // Some should be inside IfNode, and there to be a more reliable
1973   // transformation of ?: style patterns into cmoves.  We also want
1974   // more powerful optimizations around cmove and min/max.
1975 
1976   // Try to find a dominating comparison of these guys.
1977   // It can simplify the index computation for Arrays.copyOf
1978   // and similar uses of System.arraycopy.
1979   // First, compute the normalized version of CmpI(x, y).
1980   int   cmp_op = Op_CmpI;
1981   Node* xkey = xvalue;
1982   Node* ykey = yvalue;
1983   Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
1984   if (ideal_cmpxy->is_Cmp()) {
1985     // E.g., if we have CmpI(length - offset, count),
1986     // it might idealize to CmpI(length, count + offset)
1987     cmp_op = ideal_cmpxy->Opcode();
1988     xkey = ideal_cmpxy->in(1);
1989     ykey = ideal_cmpxy->in(2);
1990   }
1991 
1992   // Start by locating any relevant comparisons.
1993   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
1994   Node* cmpxy = NULL;
1995   Node* cmpyx = NULL;
1996   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
1997     Node* cmp = start_from->fast_out(k);
1998     if (cmp->outcnt() > 0 &&            // must have prior uses
1999         cmp->in(0) == NULL &&           // must be context-independent
2000         cmp->Opcode() == cmp_op) {      // right kind of compare
2001       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
2002       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
2003     }
2004   }
2005 
2006   const int NCMPS = 2;
2007   Node* cmps[NCMPS] = { cmpxy, cmpyx };
2008   int cmpn;
2009   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2010     if (cmps[cmpn] != NULL)  break;     // find a result
2011   }
2012   if (cmpn < NCMPS) {
2013     // Look for a dominating test that tells us the min and max.
2014     int depth = 0;                // Limit search depth for speed
2015     Node* dom = control();
2016     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
2017       if (++depth >= 100)  break;
2018       Node* ifproj = dom;
2019       if (!ifproj->is_Proj())  continue;
2020       Node* iff = ifproj->in(0);
2021       if (!iff->is_If())  continue;
2022       Node* bol = iff->in(1);
2023       if (!bol->is_Bool())  continue;
2024       Node* cmp = bol->in(1);
2025       if (cmp == NULL)  continue;
2026       for (cmpn = 0; cmpn < NCMPS; cmpn++)
2027         if (cmps[cmpn] == cmp)  break;
2028       if (cmpn == NCMPS)  continue;
2029       BoolTest::mask btest = bol->as_Bool()->_test._test;
2030       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
2031       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
2032       // At this point, we know that 'x btest y' is true.
2033       switch (btest) {
2034       case BoolTest::eq:
2035         // They are proven equal, so we can collapse the min/max.
2036         // Either value is the answer.  Choose the simpler.
2037         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
2038           return yvalue;
2039         return xvalue;
2040       case BoolTest::lt:          // x < y
2041       case BoolTest::le:          // x <= y
2042         return (want_max ? yvalue : xvalue);
2043       case BoolTest::gt:          // x > y
2044       case BoolTest::ge:          // x >= y
2045         return (want_max ? xvalue : yvalue);
2046       }
2047     }
2048   }
2049 
2050   // We failed to find a dominating test.
2051   // Let's pick a test that might GVN with prior tests.
2052   Node*          best_bol   = NULL;
2053   BoolTest::mask best_btest = BoolTest::illegal;
2054   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
2055     Node* cmp = cmps[cmpn];
2056     if (cmp == NULL)  continue;
2057     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
2058       Node* bol = cmp->fast_out(j);
2059       if (!bol->is_Bool())  continue;
2060       BoolTest::mask btest = bol->as_Bool()->_test._test;
2061       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
2062       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
2063       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
2064         best_bol   = bol->as_Bool();
2065         best_btest = btest;
2066       }
2067     }
2068   }
2069 
2070   Node* answer_if_true  = NULL;
2071   Node* answer_if_false = NULL;
2072   switch (best_btest) {
2073   default:
2074     if (cmpxy == NULL)
2075       cmpxy = ideal_cmpxy;
2076     best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
2077     // and fall through:
2078   case BoolTest::lt:          // x < y
2079   case BoolTest::le:          // x <= y
2080     answer_if_true  = (want_max ? yvalue : xvalue);
2081     answer_if_false = (want_max ? xvalue : yvalue);
2082     break;
2083   case BoolTest::gt:          // x > y
2084   case BoolTest::ge:          // x >= y
2085     answer_if_true  = (want_max ? xvalue : yvalue);
2086     answer_if_false = (want_max ? yvalue : xvalue);
2087     break;
2088   }
2089 
2090   jint hi, lo;
2091   if (want_max) {
2092     // We can sharpen the minimum.
2093     hi = MAX2(txvalue->_hi, tyvalue->_hi);
2094     lo = MAX2(txvalue->_lo, tyvalue->_lo);
2095   } else {
2096     // We can sharpen the maximum.
2097     hi = MIN2(txvalue->_hi, tyvalue->_hi);
2098     lo = MIN2(txvalue->_lo, tyvalue->_lo);
2099   }
2100 
2101   // Use a flow-free graph structure, to avoid creating excess control edges
2102   // which could hinder other optimizations.
2103   // Since Math.min/max is often used with arraycopy, we want
2104   // tightly_coupled_allocation to be able to see beyond min/max expressions.
2105   Node* cmov = CMoveNode::make(NULL, best_bol,
2106                                answer_if_false, answer_if_true,
2107                                TypeInt::make(lo, hi, widen));
2108 
2109   return _gvn.transform(cmov);
2110 
2111   /*
2112   // This is not as desirable as it may seem, since Min and Max
2113   // nodes do not have a full set of optimizations.
2114   // And they would interfere, anyway, with 'if' optimizations
2115   // and with CMoveI canonical forms.
2116   switch (id) {
2117   case vmIntrinsics::_min:
2118     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
2119   case vmIntrinsics::_max:
2120     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
2121   default:
2122     ShouldNotReachHere();
2123   }
2124   */
2125 }
2126 
2127 inline int
2128 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
2129   const TypePtr* base_type = TypePtr::NULL_PTR;
2130   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
2131   if (base_type == NULL) {
2132     // Unknown type.
2133     return Type::AnyPtr;
2134   } else if (base_type == TypePtr::NULL_PTR) {
2135     // Since this is a NULL+long form, we have to switch to a rawptr.
2136     base   = _gvn.transform(new CastX2PNode(offset));
2137     offset = MakeConX(0);
2138     return Type::RawPtr;
2139   } else if (base_type->base() == Type::RawPtr) {
2140     return Type::RawPtr;
2141   } else if (base_type->isa_oopptr()) {
2142     // Base is never null => always a heap address.
2143     if (base_type->ptr() == TypePtr::NotNull) {
2144       return Type::OopPtr;
2145     }
2146     // Offset is small => always a heap address.
2147     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2148     if (offset_type != NULL &&
2149         base_type->offset() == 0 &&     // (should always be?)
2150         offset_type->_lo >= 0 &&
2151         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2152       return Type::OopPtr;
2153     }
2154     // Otherwise, it might either be oop+off or NULL+addr.
2155     return Type::AnyPtr;
2156   } else {
2157     // No information:
2158     return Type::AnyPtr;
2159   }
2160 }
2161 
2162 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
2163   int kind = classify_unsafe_addr(base, offset);
2164   if (kind == Type::RawPtr) {
2165     return basic_plus_adr(top(), base, offset);
2166   } else {
2167     return basic_plus_adr(base, offset);
2168   }
2169 }
2170 
2171 //--------------------------inline_number_methods-----------------------------
2172 // inline int     Integer.numberOfLeadingZeros(int)
2173 // inline int        Long.numberOfLeadingZeros(long)
2174 //
2175 // inline int     Integer.numberOfTrailingZeros(int)
2176 // inline int        Long.numberOfTrailingZeros(long)
2177 //
2178 // inline int     Integer.bitCount(int)
2179 // inline int        Long.bitCount(long)
2180 //
2181 // inline char  Character.reverseBytes(char)
2182 // inline short     Short.reverseBytes(short)
2183 // inline int     Integer.reverseBytes(int)
2184 // inline long       Long.reverseBytes(long)
2185 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2186   Node* arg = argument(0);
2187   Node* n = NULL;
2188   switch (id) {
2189   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg);  break;
2190   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg);  break;
2191   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg);  break;
2192   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg);  break;
2193   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg);  break;
2194   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg);  break;
2195   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(0,   arg);  break;
2196   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode( 0,   arg);  break;
2197   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode( 0,   arg);  break;
2198   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode( 0,   arg);  break;
2199   default:  fatal_unexpected_iid(id);  break;
2200   }
2201   set_result(_gvn.transform(n));
2202   return true;
2203 }
2204 
2205 //----------------------------inline_unsafe_access----------------------------
2206 
2207 const static BasicType T_ADDRESS_HOLDER = T_LONG;
2208 
2209 // Helper that guards and inserts a pre-barrier.
2210 void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
2211                                         Node* pre_val, bool need_mem_bar) {
2212   // We could be accessing the referent field of a reference object. If so, when G1
2213   // is enabled, we need to log the value in the referent field in an SATB buffer.
2214   // This routine performs some compile time filters and generates suitable
2215   // runtime filters that guard the pre-barrier code.
2216   // Also add memory barrier for non volatile load from the referent field
2217   // to prevent commoning of loads across safepoint.
2218   if (!UseG1GC && !need_mem_bar)
2219     return;
2220 
2221   // Some compile time checks.
2222 
2223   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
2224   const TypeX* otype = offset->find_intptr_t_type();
2225   if (otype != NULL && otype->is_con() &&
2226       otype->get_con() != java_lang_ref_Reference::referent_offset) {
2227     // Constant offset but not the reference_offset so just return
2228     return;
2229   }
2230 
2231   // We only need to generate the runtime guards for instances.
2232   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
2233   if (btype != NULL) {
2234     if (btype->isa_aryptr()) {
2235       // Array type so nothing to do
2236       return;
2237     }
2238 
2239     const TypeInstPtr* itype = btype->isa_instptr();
2240     if (itype != NULL) {
2241       // Can the klass of base_oop be statically determined to be
2242       // _not_ a sub-class of Reference and _not_ Object?
2243       ciKlass* klass = itype->klass();
2244       if ( klass->is_loaded() &&
2245           !klass->is_subtype_of(env()->Reference_klass()) &&
2246           !env()->Object_klass()->is_subtype_of(klass)) {
2247         return;
2248       }
2249     }
2250   }
2251 
2252   // The compile time filters did not reject base_oop/offset so
2253   // we need to generate the following runtime filters
2254   //
2255   // if (offset == java_lang_ref_Reference::_reference_offset) {
2256   //   if (instance_of(base, java.lang.ref.Reference)) {
2257   //     pre_barrier(_, pre_val, ...);
2258   //   }
2259   // }
2260 
2261   float likely   = PROB_LIKELY(  0.999);
2262   float unlikely = PROB_UNLIKELY(0.999);
2263 
2264   IdealKit ideal(this);
2265 #define __ ideal.
2266 
2267   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
2268 
2269   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
2270       // Update graphKit memory and control from IdealKit.
2271       sync_kit(ideal);
2272 
2273       Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
2274       Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
2275 
2276       // Update IdealKit memory and control from graphKit.
2277       __ sync_kit(this);
2278 
2279       Node* one = __ ConI(1);
2280       // is_instof == 0 if base_oop == NULL
2281       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
2282 
2283         // Update graphKit from IdeakKit.
2284         sync_kit(ideal);
2285 
2286         // Use the pre-barrier to record the value in the referent field
2287         pre_barrier(false /* do_load */,
2288                     __ ctrl(),
2289                     NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
2290                     pre_val /* pre_val */,
2291                     T_OBJECT);
2292         if (need_mem_bar) {
2293           // Add memory barrier to prevent commoning reads from this field
2294           // across safepoint since GC can change its value.
2295           insert_mem_bar(Op_MemBarCPUOrder);
2296         }
2297         // Update IdealKit from graphKit.
2298         __ sync_kit(this);
2299 
2300       } __ end_if(); // _ref_type != ref_none
2301   } __ end_if(); // offset == referent_offset
2302 
2303   // Final sync IdealKit and GraphKit.
2304   final_sync(ideal);
2305 #undef __
2306 }
2307 
2308 
2309 // Interpret Unsafe.fieldOffset cookies correctly:
2310 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2311 
2312 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
2313   // Attempt to infer a sharper value type from the offset and base type.
2314   ciKlass* sharpened_klass = NULL;
2315 
2316   // See if it is an instance field, with an object type.
2317   if (alias_type->field() != NULL) {
2318     assert(!is_native_ptr, "native pointer op cannot use a java address");
2319     if (alias_type->field()->type()->is_klass()) {
2320       sharpened_klass = alias_type->field()->type()->as_klass();
2321     }
2322   }
2323 
2324   // See if it is a narrow oop array.
2325   if (adr_type->isa_aryptr()) {
2326     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2327       const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2328       if (elem_type != NULL) {
2329         sharpened_klass = elem_type->klass();
2330       }
2331     }
2332   }
2333 
2334   // The sharpened class might be unloaded if there is no class loader
2335   // contraint in place.
2336   if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2337     const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2338 
2339 #ifndef PRODUCT
2340     if (C->print_intrinsics() || C->print_inlining()) {
2341       tty->print("  from base type: ");  adr_type->dump();
2342       tty->print("  sharpened value: ");  tjp->dump();
2343     }
2344 #endif
2345     // Sharpen the value type.
2346     return tjp;
2347   }
2348   return NULL;
2349 }
2350 
2351 bool LibraryCallKit::inline_unsafe_access(const bool is_native_ptr, bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2352   if (callee()->is_static())  return false;  // caller must have the capability!
2353   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2354   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2355 
2356 #ifndef PRODUCT
2357   {
2358     ResourceMark rm;
2359     // Check the signatures.
2360     ciSignature* sig = callee()->signature();
2361 #ifdef ASSERT
2362     if (!is_store) {
2363       // Object getObject(Object base, int/long offset), etc.
2364       BasicType rtype = sig->return_type()->basic_type();
2365       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2366           rtype = T_ADDRESS;  // it is really a C void*
2367       assert(rtype == type, "getter must return the expected value");
2368       if (!is_native_ptr) {
2369         assert(sig->count() == 2, "oop getter has 2 arguments");
2370         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2371         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2372       } else {
2373         assert(sig->count() == 1, "native getter has 1 argument");
2374         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2375       }
2376     } else {
2377       // void putObject(Object base, int/long offset, Object x), etc.
2378       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2379       if (!is_native_ptr) {
2380         assert(sig->count() == 3, "oop putter has 3 arguments");
2381         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2382         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2383       } else {
2384         assert(sig->count() == 2, "native putter has 2 arguments");
2385         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2386       }
2387       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2388       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2389         vtype = T_ADDRESS;  // it is really a C void*
2390       assert(vtype == type, "putter must accept the expected value");
2391     }
2392 #endif // ASSERT
2393  }
2394 #endif //PRODUCT
2395 
2396   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2397 
2398   Node* receiver = argument(0);  // type: oop
2399 
2400   // Build address expression.
2401   Node* adr;
2402   Node* heap_base_oop = top();
2403   Node* offset = top();
2404   Node* val;
2405 
2406   if (!is_native_ptr) {
2407     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2408     Node* base = argument(1);  // type: oop
2409     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2410     offset = argument(2);  // type: long
2411     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2412     // to be plain byte offsets, which are also the same as those accepted
2413     // by oopDesc::field_base.
2414     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2415            "fieldOffset must be byte-scaled");
2416     // 32-bit machines ignore the high half!
2417     offset = ConvL2X(offset);
2418     adr = make_unsafe_address(base, offset);
2419     heap_base_oop = base;
2420     val = is_store ? argument(4) : NULL;
2421   } else {
2422     Node* ptr = argument(1);  // type: long
2423     ptr = ConvL2X(ptr);  // adjust Java long to machine word
2424     adr = make_unsafe_address(NULL, ptr);
2425     val = is_store ? argument(3) : NULL;
2426   }
2427 
2428   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2429 
2430   // First guess at the value type.
2431   const Type *value_type = Type::get_const_basic_type(type);
2432 
2433   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2434   // there was not enough information to nail it down.
2435   Compile::AliasType* alias_type = C->alias_type(adr_type);
2436   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2437 
2438   // We will need memory barriers unless we can determine a unique
2439   // alias category for this reference.  (Note:  If for some reason
2440   // the barriers get omitted and the unsafe reference begins to "pollute"
2441   // the alias analysis of the rest of the graph, either Compile::can_alias
2442   // or Compile::must_alias will throw a diagnostic assert.)
2443   bool need_mem_bar;
2444   switch (kind) {
2445       case Relaxed:
2446           need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2447           break;
2448       case Opaque:
2449           // Opaque uses CPUOrder membars for protection against code movement.
2450       case Acquire:
2451       case Release:
2452       case Volatile:
2453           need_mem_bar = true;
2454           break;
2455       default:
2456           ShouldNotReachHere();
2457   }
2458 
2459   // Some accesses require access atomicity for all types, notably longs and doubles.
2460   // When AlwaysAtomicAccesses is enabled, all accesses are atomic.
2461   bool requires_atomic_access = false;
2462   switch (kind) {
2463       case Relaxed:
2464       case Opaque:
2465           requires_atomic_access = AlwaysAtomicAccesses;
2466           break;
2467       case Acquire:
2468       case Release:
2469       case Volatile:
2470           requires_atomic_access = true;
2471           break;
2472       default:
2473           ShouldNotReachHere();
2474   }
2475 
2476   // Figure out the memory ordering.
2477   // Acquire/Release/Volatile accesses require marking the loads/stores with MemOrd
2478   MemNode::MemOrd mo = access_kind_to_memord_LS(kind, is_store);
2479 
2480   // If we are reading the value of the referent field of a Reference
2481   // object (either by using Unsafe directly or through reflection)
2482   // then, if G1 is enabled, we need to record the referent in an
2483   // SATB log buffer using the pre-barrier mechanism.
2484   // Also we need to add memory barrier to prevent commoning reads
2485   // from this field across safepoint since GC can change its value.
2486   bool need_read_barrier = !is_native_ptr && !is_store &&
2487                            offset != top() && heap_base_oop != top();
2488 
2489   if (!is_store && type == T_OBJECT) {
2490     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
2491     if (tjp != NULL) {
2492       value_type = tjp;
2493     }
2494   }
2495 
2496   receiver = null_check(receiver);
2497   if (stopped()) {
2498     return true;
2499   }
2500   // Heap pointers get a null-check from the interpreter,
2501   // as a courtesy.  However, this is not guaranteed by Unsafe,
2502   // and it is not possible to fully distinguish unintended nulls
2503   // from intended ones in this API.
2504 
2505   // We need to emit leading and trailing CPU membars (see below) in
2506   // addition to memory membars for special access modes. This is a little
2507   // too strong, but avoids the need to insert per-alias-type
2508   // volatile membars (for stores; compare Parse::do_put_xxx), which
2509   // we cannot do effectively here because we probably only have a
2510   // rough approximation of type.
2511 
2512   switch(kind) {
2513     case Relaxed:
2514     case Opaque:
2515     case Acquire:
2516       break;
2517     case Release:
2518     case Volatile:
2519       if (is_store) {
2520         insert_mem_bar(Op_MemBarRelease);
2521       } else {
2522         if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
2523           insert_mem_bar(Op_MemBarVolatile);
2524         }
2525       }
2526       break;
2527     default:
2528       ShouldNotReachHere();
2529   }
2530 
2531   // Memory barrier to prevent normal and 'unsafe' accesses from
2532   // bypassing each other.  Happens after null checks, so the
2533   // exception paths do not take memory state from the memory barrier,
2534   // so there's no problems making a strong assert about mixing users
2535   // of safe & unsafe memory.
2536   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2537 
2538   assert(alias_type->adr_type() == TypeRawPtr::BOTTOM || alias_type->adr_type() == TypeOopPtr::BOTTOM ||
2539          alias_type->field() != NULL || alias_type->element() != NULL, "field, array element or unknown");
2540   bool mismatched = false;
2541   if (alias_type->element() != NULL || alias_type->field() != NULL) {
2542     BasicType bt;
2543     if (alias_type->element() != NULL) {
2544       const Type* element = alias_type->element();
2545       bt = element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
2546     } else {
2547       bt = alias_type->field()->type()->basic_type();
2548     }
2549     if (bt == T_ARRAY) {
2550       // accessing an array field with getObject is not a mismatch
2551       bt = T_OBJECT;
2552     }
2553     if (bt != type) {
2554       mismatched = true;
2555     }
2556   }
2557   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2558 
2559   if (!is_store) {
2560     Node* p = NULL;
2561     // Try to constant fold a load from a constant field
2562     ciField* field = alias_type->field();
2563     if (heap_base_oop != top() &&
2564         field != NULL && field->is_constant() && field->layout_type() == type) {
2565       // final or stable field
2566       const Type* con_type = Type::make_constant(alias_type->field(), heap_base_oop);
2567       if (con_type != NULL) {
2568         p = makecon(con_type);
2569       }
2570     }
2571     if (p == NULL) {
2572       // To be valid, unsafe loads may depend on other conditions than
2573       // the one that guards them: pin the Load node
2574       p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, requires_atomic_access, unaligned, mismatched);
2575       // load value
2576       switch (type) {
2577       case T_BOOLEAN:
2578       case T_CHAR:
2579       case T_BYTE:
2580       case T_SHORT:
2581       case T_INT:
2582       case T_LONG:
2583       case T_FLOAT:
2584       case T_DOUBLE:
2585         break;
2586       case T_OBJECT:
2587         if (need_read_barrier) {
2588           // We do not require a mem bar inside pre_barrier if need_mem_bar
2589           // is set: the barriers would be emitted by us.
2590           insert_pre_barrier(heap_base_oop, offset, p, !need_mem_bar);
2591         }
2592         break;
2593       case T_ADDRESS:
2594         // Cast to an int type.
2595         p = _gvn.transform(new CastP2XNode(NULL, p));
2596         p = ConvX2UL(p);
2597         break;
2598       default:
2599         fatal("unexpected type %d: %s", type, type2name(type));
2600         break;
2601       }
2602     }
2603     // The load node has the control of the preceding MemBarCPUOrder.  All
2604     // following nodes will have the control of the MemBarCPUOrder inserted at
2605     // the end of this method.  So, pushing the load onto the stack at a later
2606     // point is fine.
2607     set_result(p);
2608   } else {
2609     // place effect of store into memory
2610     switch (type) {
2611     case T_DOUBLE:
2612       val = dstore_rounding(val);
2613       break;
2614     case T_ADDRESS:
2615       // Repackage the long as a pointer.
2616       val = ConvL2X(val);
2617       val = _gvn.transform(new CastX2PNode(val));
2618       break;
2619     }
2620 
2621     if (type != T_OBJECT) {
2622       (void) store_to_memory(control(), adr, val, type, adr_type, mo, requires_atomic_access, unaligned, mismatched);
2623     } else {
2624       // Possibly an oop being stored to Java heap or native memory
2625       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2626         // oop to Java heap.
2627         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);
2628       } else {
2629         // We can't tell at compile time if we are storing in the Java heap or outside
2630         // of it. So we need to emit code to conditionally do the proper type of
2631         // store.
2632 
2633         IdealKit ideal(this);
2634 #define __ ideal.
2635         // QQQ who knows what probability is here??
2636         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2637           // Sync IdealKit and graphKit.
2638           sync_kit(ideal);
2639           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);
2640           // Update IdealKit memory.
2641           __ sync_kit(this);
2642         } __ else_(); {
2643           __ store(__ ctrl(), adr, val, type, alias_type->index(), mo, requires_atomic_access, mismatched);
2644         } __ end_if();
2645         // Final sync IdealKit and GraphKit.
2646         final_sync(ideal);
2647 #undef __
2648       }
2649     }
2650   }
2651 
2652   switch(kind) {
2653     case Relaxed:
2654     case Opaque:
2655     case Release:
2656       break;
2657     case Acquire:
2658     case Volatile:
2659       if (!is_store) {
2660         insert_mem_bar(Op_MemBarAcquire);
2661       } else {
2662         if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
2663           insert_mem_bar(Op_MemBarVolatile);
2664         }
2665       }
2666       break;
2667     default:
2668       ShouldNotReachHere();
2669   }
2670 
2671   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2672 
2673   return true;
2674 }
2675 
2676 //----------------------------inline_unsafe_load_store----------------------------
2677 // This method serves a couple of different customers (depending on LoadStoreKind):
2678 //
2679 // LS_cmp_swap:
2680 //
2681 //   boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
2682 //   boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
2683 //   boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
2684 //
2685 // LS_cmp_swap_weak:
2686 //
2687 //   boolean weakCompareAndSwapObject(       Object o, long offset, Object expected, Object x);
2688 //   boolean weakCompareAndSwapObjectAcquire(Object o, long offset, Object expected, Object x);
2689 //   boolean weakCompareAndSwapObjectRelease(Object o, long offset, Object expected, Object x);
2690 //
2691 //   boolean weakCompareAndSwapInt(          Object o, long offset, int    expected, int    x);
2692 //   boolean weakCompareAndSwapIntAcquire(   Object o, long offset, int    expected, int    x);
2693 //   boolean weakCompareAndSwapIntRelease(   Object o, long offset, int    expected, int    x);
2694 //
2695 //   boolean weakCompareAndSwapLong(         Object o, long offset, long   expected, long   x);
2696 //   boolean weakCompareAndSwapLongAcquire(  Object o, long offset, long   expected, long   x);
2697 //   boolean weakCompareAndSwapLongRelease(  Object o, long offset, long   expected, long   x);
2698 //
2699 // LS_cmp_exchange:
2700 //
2701 //   Object compareAndExchangeObjectVolatile(Object o, long offset, Object expected, Object x);
2702 //   Object compareAndExchangeObjectAcquire( Object o, long offset, Object expected, Object x);
2703 //   Object compareAndExchangeObjectRelease( Object o, long offset, Object expected, Object x);
2704 //
2705 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2706 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2707 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2708 //
2709 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2710 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2711 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2712 //
2713 // LS_get_add:
2714 //
2715 //   int  getAndAddInt( Object o, long offset, int  delta)
2716 //   long getAndAddLong(Object o, long offset, long delta)
2717 //
2718 // LS_get_set:
2719 //
2720 //   int    getAndSet(Object o, long offset, int    newValue)
2721 //   long   getAndSet(Object o, long offset, long   newValue)
2722 //   Object getAndSet(Object o, long offset, Object newValue)
2723 //
2724 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2725   // This basic scheme here is the same as inline_unsafe_access, but
2726   // differs in enough details that combining them would make the code
2727   // overly confusing.  (This is a true fact! I originally combined
2728   // them, but even I was confused by it!) As much code/comments as
2729   // possible are retained from inline_unsafe_access though to make
2730   // the correspondences clearer. - dl
2731 
2732   if (callee()->is_static())  return false;  // caller must have the capability!
2733 
2734 #ifndef PRODUCT
2735   BasicType rtype;
2736   {
2737     ResourceMark rm;
2738     // Check the signatures.
2739     ciSignature* sig = callee()->signature();
2740     rtype = sig->return_type()->basic_type();
2741     switch(kind) {
2742       case LS_get_add:
2743       case LS_get_set: {
2744       // Check the signatures.
2745 #ifdef ASSERT
2746       assert(rtype == type, "get and set must return the expected type");
2747       assert(sig->count() == 3, "get and set has 3 arguments");
2748       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2749       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2750       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2751 #endif // ASSERT
2752         break;
2753       }
2754       case LS_cmp_swap:
2755       case LS_cmp_swap_weak: {
2756       // Check the signatures.
2757 #ifdef ASSERT
2758       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2759       assert(sig->count() == 4, "CAS has 4 arguments");
2760       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2761       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2762 #endif // ASSERT
2763         break;
2764       }
2765       case LS_cmp_exchange: {
2766       // Check the signatures.
2767 #ifdef ASSERT
2768       assert(rtype == type, "CAS must return the expected type");
2769       assert(sig->count() == 4, "CAS has 4 arguments");
2770       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2771       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2772 #endif // ASSERT
2773         break;
2774       }
2775       default:
2776         ShouldNotReachHere();
2777     }
2778   }
2779 #endif //PRODUCT
2780 
2781   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2782 
2783   // Get arguments:
2784   Node* receiver = NULL;
2785   Node* base     = NULL;
2786   Node* offset   = NULL;
2787   Node* oldval   = NULL;
2788   Node* newval   = NULL;
2789   switch(kind) {
2790     case LS_cmp_swap:
2791     case LS_cmp_swap_weak:
2792     case LS_cmp_exchange: {
2793       const bool two_slot_type = type2size[type] == 2;
2794       receiver = argument(0);  // type: oop
2795       base     = argument(1);  // type: oop
2796       offset   = argument(2);  // type: long
2797       oldval   = argument(4);  // type: oop, int, or long
2798       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2799       break;
2800     }
2801     case LS_get_add:
2802     case LS_get_set: {
2803       receiver = argument(0);  // type: oop
2804       base     = argument(1);  // type: oop
2805       offset   = argument(2);  // type: long
2806       oldval   = NULL;
2807       newval   = argument(4);  // type: oop, int, or long
2808       break;
2809     }
2810     default:
2811       ShouldNotReachHere();
2812   }
2813 
2814   // Null check receiver.
2815   receiver = null_check(receiver);
2816   if (stopped()) {
2817     return true;
2818   }
2819 
2820   // Build field offset expression.
2821   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2822   // to be plain byte offsets, which are also the same as those accepted
2823   // by oopDesc::field_base.
2824   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2825   // 32-bit machines ignore the high half of long offsets
2826   offset = ConvL2X(offset);
2827   Node* adr = make_unsafe_address(base, offset);
2828   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2829 
2830   // For CAS, unlike inline_unsafe_access, there seems no point in
2831   // trying to refine types. Just use the coarse types here.
2832   const Type *value_type = Type::get_const_basic_type(type);
2833   Compile::AliasType* alias_type = C->alias_type(adr_type);
2834   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2835 
2836   switch (kind) {
2837     case LS_get_set:
2838     case LS_cmp_exchange: {
2839       if (type == T_OBJECT) {
2840         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2841         if (tjp != NULL) {
2842           value_type = tjp;
2843         }
2844       }
2845       break;
2846     }
2847     case LS_cmp_swap:
2848     case LS_cmp_swap_weak:
2849     case LS_get_add:
2850       break;
2851     default:
2852       ShouldNotReachHere();
2853   }
2854 
2855   int alias_idx = C->get_alias_index(adr_type);
2856 
2857   // Memory-model-wise, a LoadStore acts like a little synchronized
2858   // block, so needs barriers on each side.  These don't translate
2859   // into actual barriers on most machines, but we still need rest of
2860   // compiler to respect ordering.
2861 
2862   switch (access_kind) {
2863     case Relaxed:
2864     case Acquire:
2865       break;
2866     case Release:
2867     case Volatile:
2868       insert_mem_bar(Op_MemBarRelease);
2869       break;
2870     default:
2871       ShouldNotReachHere();
2872   }
2873   insert_mem_bar(Op_MemBarCPUOrder);
2874 
2875   // Figure out the memory ordering.
2876   MemNode::MemOrd mo = access_kind_to_memord(access_kind);
2877 
2878   // 4984716: MemBars must be inserted before this
2879   //          memory node in order to avoid a false
2880   //          dependency which will confuse the scheduler.
2881   Node *mem = memory(alias_idx);
2882 
2883   // For now, we handle only those cases that actually exist: ints,
2884   // longs, and Object. Adding others should be straightforward.
2885   Node* load_store = NULL;
2886   switch(type) {
2887   case T_INT:
2888     switch(kind) {
2889       case LS_get_add:
2890         load_store = _gvn.transform(new GetAndAddINode(control(), mem, adr, newval, adr_type));
2891         break;
2892       case LS_get_set:
2893         load_store = _gvn.transform(new GetAndSetINode(control(), mem, adr, newval, adr_type));
2894         break;
2895       case LS_cmp_swap_weak:
2896         load_store = _gvn.transform(new WeakCompareAndSwapINode(control(), mem, adr, newval, oldval, mo));
2897         break;
2898       case LS_cmp_swap:
2899         load_store = _gvn.transform(new CompareAndSwapINode(control(), mem, adr, newval, oldval, mo));
2900         break;
2901       case LS_cmp_exchange:
2902         load_store = _gvn.transform(new CompareAndExchangeINode(control(), mem, adr, newval, oldval, adr_type, mo));
2903         break;
2904       default:
2905         ShouldNotReachHere();
2906     }
2907     break;
2908   case T_LONG:
2909     switch(kind) {
2910       case LS_get_add:
2911         load_store = _gvn.transform(new GetAndAddLNode(control(), mem, adr, newval, adr_type));
2912         break;
2913       case LS_get_set:
2914         load_store = _gvn.transform(new GetAndSetLNode(control(), mem, adr, newval, adr_type));
2915         break;
2916       case LS_cmp_swap_weak:
2917         load_store = _gvn.transform(new WeakCompareAndSwapLNode(control(), mem, adr, newval, oldval, mo));
2918         break;
2919       case LS_cmp_swap:
2920         load_store = _gvn.transform(new CompareAndSwapLNode(control(), mem, adr, newval, oldval, mo));
2921         break;
2922       case LS_cmp_exchange:
2923         load_store = _gvn.transform(new CompareAndExchangeLNode(control(), mem, adr, newval, oldval, adr_type, mo));
2924         break;
2925       default:
2926         ShouldNotReachHere();
2927     }
2928     break;
2929   case T_OBJECT:
2930     // Transformation of a value which could be NULL pointer (CastPP #NULL)
2931     // could be delayed during Parse (for example, in adjust_map_after_if()).
2932     // Execute transformation here to avoid barrier generation in such case.
2933     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2934       newval = _gvn.makecon(TypePtr::NULL_PTR);
2935 
2936     // Reference stores need a store barrier.
2937     switch(kind) {
2938       case LS_get_set: {
2939         // If pre-barrier must execute before the oop store, old value will require do_load here.
2940         if (!can_move_pre_barrier()) {
2941           pre_barrier(true /* do_load*/,
2942                       control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
2943                       NULL /* pre_val*/,
2944                       T_OBJECT);
2945         } // Else move pre_barrier to use load_store value, see below.
2946         break;
2947       }
2948       case LS_cmp_swap_weak:
2949       case LS_cmp_swap:
2950       case LS_cmp_exchange: {
2951         // Same as for newval above:
2952         if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
2953           oldval = _gvn.makecon(TypePtr::NULL_PTR);
2954         }
2955         // The only known value which might get overwritten is oldval.
2956         pre_barrier(false /* do_load */,
2957                     control(), NULL, NULL, max_juint, NULL, NULL,
2958                     oldval /* pre_val */,
2959                     T_OBJECT);
2960         break;
2961       }
2962       default:
2963         ShouldNotReachHere();
2964     }
2965 
2966 #ifdef _LP64
2967     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2968       Node *newval_enc = _gvn.transform(new EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2969 
2970       switch(kind) {
2971         case LS_get_set:
2972           load_store = _gvn.transform(new GetAndSetNNode(control(), mem, adr, newval_enc, adr_type, value_type->make_narrowoop()));
2973           break;
2974         case LS_cmp_swap_weak: {
2975           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2976           load_store = _gvn.transform(new WeakCompareAndSwapNNode(control(), mem, adr, newval_enc, oldval_enc, mo));
2977           break;
2978         }
2979         case LS_cmp_swap: {
2980           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2981           load_store = _gvn.transform(new CompareAndSwapNNode(control(), mem, adr, newval_enc, oldval_enc, mo));
2982           break;
2983         }
2984         case LS_cmp_exchange: {
2985           Node *oldval_enc = _gvn.transform(new EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2986           load_store = _gvn.transform(new CompareAndExchangeNNode(control(), mem, adr, newval_enc, oldval_enc, adr_type, value_type->make_narrowoop(), mo));
2987           break;
2988         }
2989         default:
2990           ShouldNotReachHere();
2991       }
2992     } else
2993 #endif
2994     switch (kind) {
2995       case LS_get_set:
2996         load_store = _gvn.transform(new GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
2997         break;
2998       case LS_cmp_swap_weak:
2999         load_store = _gvn.transform(new WeakCompareAndSwapPNode(control(), mem, adr, newval, oldval, mo));
3000         break;
3001       case LS_cmp_swap:
3002         load_store = _gvn.transform(new CompareAndSwapPNode(control(), mem, adr, newval, oldval, mo));
3003         break;
3004       case LS_cmp_exchange:
3005         load_store = _gvn.transform(new CompareAndExchangePNode(control(), mem, adr, newval, oldval, adr_type, value_type->is_oopptr(), mo));
3006         break;
3007       default:
3008         ShouldNotReachHere();
3009     }
3010 
3011     // Emit the post barrier only when the actual store happened. This makes sense
3012     // to check only for LS_cmp_* that can fail to set the value.
3013     // LS_cmp_exchange does not produce any branches by default, so there is no
3014     // boolean result to piggyback on. TODO: When we merge CompareAndSwap with
3015     // CompareAndExchange and move branches here, it would make sense to conditionalize
3016     // post_barriers for LS_cmp_exchange as well.
3017     //
3018     // CAS success path is marked more likely since we anticipate this is a performance
3019     // critical path, while CAS failure path can use the penalty for going through unlikely
3020     // path as backoff. Which is still better than doing a store barrier there.
3021     switch (kind) {
3022       case LS_get_set:
3023       case LS_cmp_exchange: {
3024         post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3025         break;
3026       }
3027       case LS_cmp_swap_weak:
3028       case LS_cmp_swap: {
3029         IdealKit ideal(this);
3030         ideal.if_then(load_store, BoolTest::ne, ideal.ConI(0), PROB_STATIC_FREQUENT); {
3031           sync_kit(ideal);
3032           post_barrier(ideal.ctrl(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
3033           ideal.sync_kit(this);
3034         } ideal.end_if();
3035         final_sync(ideal);
3036         break;
3037       }
3038       default:
3039         ShouldNotReachHere();
3040     }
3041     break;
3042   default:
3043     fatal("unexpected type %d: %s", type, type2name(type));
3044     break;
3045   }
3046 
3047   // SCMemProjNodes represent the memory state of a LoadStore. Their
3048   // main role is to prevent LoadStore nodes from being optimized away
3049   // when their results aren't used.
3050   Node* proj = _gvn.transform(new SCMemProjNode(load_store));
3051   set_memory(proj, alias_idx);
3052 
3053   if (type == T_OBJECT && (kind == LS_get_set || kind == LS_cmp_exchange)) {
3054 #ifdef _LP64
3055     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
3056       load_store = _gvn.transform(new DecodeNNode(load_store, load_store->get_ptr_type()));
3057     }
3058 #endif
3059     if (can_move_pre_barrier()) {
3060       // Don't need to load pre_val. The old value is returned by load_store.
3061       // The pre_barrier can execute after the xchg as long as no safepoint
3062       // gets inserted between them.
3063       pre_barrier(false /* do_load */,
3064                   control(), NULL, NULL, max_juint, NULL, NULL,
3065                   load_store /* pre_val */,
3066                   T_OBJECT);
3067     }
3068   }
3069 
3070   // Add the trailing membar surrounding the access
3071   insert_mem_bar(Op_MemBarCPUOrder);
3072 
3073   switch (access_kind) {
3074     case Relaxed:
3075     case Release:
3076       break; // do nothing
3077     case Acquire:
3078     case Volatile:
3079       insert_mem_bar(Op_MemBarAcquire);
3080       break;
3081     default:
3082       ShouldNotReachHere();
3083   }
3084 
3085   assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3086   set_result(load_store);
3087   return true;
3088 }
3089 
3090 MemNode::MemOrd LibraryCallKit::access_kind_to_memord_LS(AccessKind kind, bool is_store) {
3091   MemNode::MemOrd mo = MemNode::unset;
3092   switch(kind) {
3093     case Opaque:
3094     case Relaxed:  mo = MemNode::unordered; break;
3095     case Acquire:  mo = MemNode::acquire;   break;
3096     case Release:  mo = MemNode::release;   break;
3097     case Volatile: mo = is_store ? MemNode::release : MemNode::acquire; break;
3098     default:
3099       ShouldNotReachHere();
3100   }
3101   guarantee(mo != MemNode::unset, "Should select memory ordering");
3102   return mo;
3103 }
3104 
3105 MemNode::MemOrd LibraryCallKit::access_kind_to_memord(AccessKind kind) {
3106   MemNode::MemOrd mo = MemNode::unset;
3107   switch(kind) {
3108     case Opaque:
3109     case Relaxed:  mo = MemNode::unordered; break;
3110     case Acquire:  mo = MemNode::acquire;   break;
3111     case Release:  mo = MemNode::release;   break;
3112     case Volatile: mo = MemNode::seqcst;    break;
3113     default:
3114       ShouldNotReachHere();
3115   }
3116   guarantee(mo != MemNode::unset, "Should select memory ordering");
3117   return mo;
3118 }
3119 
3120 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3121   // Regardless of form, don't allow previous ld/st to move down,
3122   // then issue acquire, release, or volatile mem_bar.
3123   insert_mem_bar(Op_MemBarCPUOrder);
3124   switch(id) {
3125     case vmIntrinsics::_loadFence:
3126       insert_mem_bar(Op_LoadFence);
3127       return true;
3128     case vmIntrinsics::_storeFence:
3129       insert_mem_bar(Op_StoreFence);
3130       return true;
3131     case vmIntrinsics::_fullFence:
3132       insert_mem_bar(Op_MemBarVolatile);
3133       return true;
3134     default:
3135       fatal_unexpected_iid(id);
3136       return false;
3137   }
3138 }
3139 
3140 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3141   if (!kls->is_Con()) {
3142     return true;
3143   }
3144   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
3145   if (klsptr == NULL) {
3146     return true;
3147   }
3148   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
3149   // don't need a guard for a klass that is already initialized
3150   return !ik->is_initialized();
3151 }
3152 
3153 //----------------------------inline_unsafe_allocate---------------------------
3154 // public native Object Unsafe.allocateInstance(Class<?> cls);
3155 bool LibraryCallKit::inline_unsafe_allocate() {
3156   if (callee()->is_static())  return false;  // caller must have the capability!
3157 
3158   null_check_receiver();  // null-check, then ignore
3159   Node* cls = null_check(argument(1));
3160   if (stopped())  return true;
3161 
3162   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3163   kls = null_check(kls);
3164   if (stopped())  return true;  // argument was like int.class
3165 
3166   Node* test = NULL;
3167   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3168     // Note:  The argument might still be an illegal value like
3169     // Serializable.class or Object[].class.   The runtime will handle it.
3170     // But we must make an explicit check for initialization.
3171     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3172     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3173     // can generate code to load it as unsigned byte.
3174     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
3175     Node* bits = intcon(InstanceKlass::fully_initialized);
3176     test = _gvn.transform(new SubINode(inst, bits));
3177     // The 'test' is non-zero if we need to take a slow path.
3178   }
3179 
3180   Node* obj = new_instance(kls, test);
3181   set_result(obj);
3182   return true;
3183 }
3184 
3185 #ifdef TRACE_HAVE_INTRINSICS
3186 /*
3187  * oop -> myklass
3188  * myklass->trace_id |= USED
3189  * return myklass->trace_id & ~0x3
3190  */
3191 bool LibraryCallKit::inline_native_classID() {
3192   null_check_receiver();  // null-check, then ignore
3193   Node* cls = null_check(argument(1), T_OBJECT);
3194   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
3195   kls = null_check(kls, T_OBJECT);
3196   ByteSize offset = TRACE_ID_OFFSET;
3197   Node* insp = basic_plus_adr(kls, in_bytes(offset));
3198   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
3199   Node* bits = longcon(~0x03l); // ignore bit 0 & 1
3200   Node* andl = _gvn.transform(new AndLNode(tvalue, bits));
3201   Node* clsused = longcon(0x01l); // set the class bit
3202   Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
3203 
3204   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
3205   store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
3206   set_result(andl);
3207   return true;
3208 }
3209 
3210 bool LibraryCallKit::inline_native_threadID() {
3211   Node* tls_ptr = NULL;
3212   Node* cur_thr = generate_current_thread(tls_ptr);
3213   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3214   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3215   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::thread_id_offset()));
3216 
3217   Node* threadid = NULL;
3218   size_t thread_id_size = OSThread::thread_id_size();
3219   if (thread_id_size == (size_t) BytesPerLong) {
3220     threadid = ConvL2I(make_load(control(), p, TypeLong::LONG, T_LONG, MemNode::unordered));
3221   } else if (thread_id_size == (size_t) BytesPerInt) {
3222     threadid = make_load(control(), p, TypeInt::INT, T_INT, MemNode::unordered);
3223   } else {
3224     ShouldNotReachHere();
3225   }
3226   set_result(threadid);
3227   return true;
3228 }
3229 #endif
3230 
3231 //------------------------inline_native_time_funcs--------------
3232 // inline code for System.currentTimeMillis() and System.nanoTime()
3233 // these have the same type and signature
3234 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3235   const TypeFunc* tf = OptoRuntime::void_long_Type();
3236   const TypePtr* no_memory_effects = NULL;
3237   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3238   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3239 #ifdef ASSERT
3240   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3241   assert(value_top == top(), "second value must be top");
3242 #endif
3243   set_result(value);
3244   return true;
3245 }
3246 
3247 //------------------------inline_native_currentThread------------------
3248 bool LibraryCallKit::inline_native_currentThread() {
3249   Node* junk = NULL;
3250   set_result(generate_current_thread(junk));
3251   return true;
3252 }
3253 
3254 //------------------------inline_native_isInterrupted------------------
3255 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
3256 bool LibraryCallKit::inline_native_isInterrupted() {
3257   // Add a fast path to t.isInterrupted(clear_int):
3258   //   (t == Thread.current() &&
3259   //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
3260   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
3261   // So, in the common case that the interrupt bit is false,
3262   // we avoid making a call into the VM.  Even if the interrupt bit
3263   // is true, if the clear_int argument is false, we avoid the VM call.
3264   // However, if the receiver is not currentThread, we must call the VM,
3265   // because there must be some locking done around the operation.
3266 
3267   // We only go to the fast case code if we pass two guards.
3268   // Paths which do not pass are accumulated in the slow_region.
3269 
3270   enum {
3271     no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
3272     no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
3273     slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
3274     PATH_LIMIT
3275   };
3276 
3277   // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
3278   // out of the function.
3279   insert_mem_bar(Op_MemBarCPUOrder);
3280 
3281   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3282   PhiNode*    result_val = new PhiNode(result_rgn, TypeInt::BOOL);
3283 
3284   RegionNode* slow_region = new RegionNode(1);
3285   record_for_igvn(slow_region);
3286 
3287   // (a) Receiving thread must be the current thread.
3288   Node* rec_thr = argument(0);
3289   Node* tls_ptr = NULL;
3290   Node* cur_thr = generate_current_thread(tls_ptr);
3291   Node* cmp_thr = _gvn.transform(new CmpPNode(cur_thr, rec_thr));
3292   Node* bol_thr = _gvn.transform(new BoolNode(cmp_thr, BoolTest::ne));
3293 
3294   generate_slow_guard(bol_thr, slow_region);
3295 
3296   // (b) Interrupt bit on TLS must be false.
3297   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
3298   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3299   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
3300 
3301   // Set the control input on the field _interrupted read to prevent it floating up.
3302   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
3303   Node* cmp_bit = _gvn.transform(new CmpINode(int_bit, intcon(0)));
3304   Node* bol_bit = _gvn.transform(new BoolNode(cmp_bit, BoolTest::ne));
3305 
3306   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
3307 
3308   // First fast path:  if (!TLS._interrupted) return false;
3309   Node* false_bit = _gvn.transform(new IfFalseNode(iff_bit));
3310   result_rgn->init_req(no_int_result_path, false_bit);
3311   result_val->init_req(no_int_result_path, intcon(0));
3312 
3313   // drop through to next case
3314   set_control( _gvn.transform(new IfTrueNode(iff_bit)));
3315 
3316 #ifndef TARGET_OS_FAMILY_windows
3317   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
3318   Node* clr_arg = argument(1);
3319   Node* cmp_arg = _gvn.transform(new CmpINode(clr_arg, intcon(0)));
3320   Node* bol_arg = _gvn.transform(new BoolNode(cmp_arg, BoolTest::ne));
3321   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
3322 
3323   // Second fast path:  ... else if (!clear_int) return true;
3324   Node* false_arg = _gvn.transform(new IfFalseNode(iff_arg));
3325   result_rgn->init_req(no_clear_result_path, false_arg);
3326   result_val->init_req(no_clear_result_path, intcon(1));
3327 
3328   // drop through to next case
3329   set_control( _gvn.transform(new IfTrueNode(iff_arg)));
3330 #else
3331   // To return true on Windows you must read the _interrupted field
3332   // and check the event state i.e. take the slow path.
3333 #endif // TARGET_OS_FAMILY_windows
3334 
3335   // (d) Otherwise, go to the slow path.
3336   slow_region->add_req(control());
3337   set_control( _gvn.transform(slow_region));
3338 
3339   if (stopped()) {
3340     // There is no slow path.
3341     result_rgn->init_req(slow_result_path, top());
3342     result_val->init_req(slow_result_path, top());
3343   } else {
3344     // non-virtual because it is a private non-static
3345     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
3346 
3347     Node* slow_val = set_results_for_java_call(slow_call);
3348     // this->control() comes from set_results_for_java_call
3349 
3350     Node* fast_io  = slow_call->in(TypeFunc::I_O);
3351     Node* fast_mem = slow_call->in(TypeFunc::Memory);
3352 
3353     // These two phis are pre-filled with copies of of the fast IO and Memory
3354     PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
3355     PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
3356 
3357     result_rgn->init_req(slow_result_path, control());
3358     result_io ->init_req(slow_result_path, i_o());
3359     result_mem->init_req(slow_result_path, reset_memory());
3360     result_val->init_req(slow_result_path, slow_val);
3361 
3362     set_all_memory(_gvn.transform(result_mem));
3363     set_i_o(       _gvn.transform(result_io));
3364   }
3365 
3366   C->set_has_split_ifs(true); // Has chance for split-if optimization
3367   set_result(result_rgn, result_val);
3368   return true;
3369 }
3370 
3371 //---------------------------load_mirror_from_klass----------------------------
3372 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3373 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3374   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
3375   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
3376 }
3377 
3378 //-----------------------load_klass_from_mirror_common-------------------------
3379 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
3380 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
3381 // and branch to the given path on the region.
3382 // If never_see_null, take an uncommon trap on null, so we can optimistically
3383 // compile for the non-null case.
3384 // If the region is NULL, force never_see_null = true.
3385 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
3386                                                     bool never_see_null,
3387                                                     RegionNode* region,
3388                                                     int null_path,
3389                                                     int offset) {
3390   if (region == NULL)  never_see_null = true;
3391   Node* p = basic_plus_adr(mirror, offset);
3392   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3393   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
3394   Node* null_ctl = top();
3395   kls = null_check_oop(kls, &null_ctl, never_see_null);
3396   if (region != NULL) {
3397     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
3398     region->init_req(null_path, null_ctl);
3399   } else {
3400     assert(null_ctl == top(), "no loose ends");
3401   }
3402   return kls;
3403 }
3404 
3405 //--------------------(inline_native_Class_query helpers)---------------------
3406 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE_FAST, JVM_ACC_HAS_FINALIZER.
3407 // Fall through if (mods & mask) == bits, take the guard otherwise.
3408 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3409   // Branch around if the given klass has the given modifier bit set.
3410   // Like generate_guard, adds a new path onto the region.
3411   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3412   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
3413   Node* mask = intcon(modifier_mask);
3414   Node* bits = intcon(modifier_bits);
3415   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3416   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3417   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3418   return generate_fair_guard(bol, region);
3419 }
3420 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3421   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
3422 }
3423 
3424 //-------------------------inline_native_Class_query-------------------
3425 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3426   const Type* return_type = TypeInt::BOOL;
3427   Node* prim_return_value = top();  // what happens if it's a primitive class?
3428   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3429   bool expect_prim = false;     // most of these guys expect to work on refs
3430 
3431   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
3432 
3433   Node* mirror = argument(0);
3434   Node* obj    = top();
3435 
3436   switch (id) {
3437   case vmIntrinsics::_isInstance:
3438     // nothing is an instance of a primitive type
3439     prim_return_value = intcon(0);
3440     obj = argument(1);
3441     break;
3442   case vmIntrinsics::_getModifiers:
3443     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3444     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
3445     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
3446     break;
3447   case vmIntrinsics::_isInterface:
3448     prim_return_value = intcon(0);
3449     break;
3450   case vmIntrinsics::_isArray:
3451     prim_return_value = intcon(0);
3452     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
3453     break;
3454   case vmIntrinsics::_isPrimitive:
3455     prim_return_value = intcon(1);
3456     expect_prim = true;  // obviously
3457     break;
3458   case vmIntrinsics::_getSuperclass:
3459     prim_return_value = null();
3460     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
3461     break;
3462   case vmIntrinsics::_getClassAccessFlags:
3463     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
3464     return_type = TypeInt::INT;  // not bool!  6297094
3465     break;
3466   default:
3467     fatal_unexpected_iid(id);
3468     break;
3469   }
3470 
3471   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3472   if (mirror_con == NULL)  return false;  // cannot happen?
3473 
3474 #ifndef PRODUCT
3475   if (C->print_intrinsics() || C->print_inlining()) {
3476     ciType* k = mirror_con->java_mirror_type();
3477     if (k) {
3478       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
3479       k->print_name();
3480       tty->cr();
3481     }
3482   }
3483 #endif
3484 
3485   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
3486   RegionNode* region = new RegionNode(PATH_LIMIT);
3487   record_for_igvn(region);
3488   PhiNode* phi = new PhiNode(region, return_type);
3489 
3490   // The mirror will never be null of Reflection.getClassAccessFlags, however
3491   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
3492   // if it is. See bug 4774291.
3493 
3494   // For Reflection.getClassAccessFlags(), the null check occurs in
3495   // the wrong place; see inline_unsafe_access(), above, for a similar
3496   // situation.
3497   mirror = null_check(mirror);
3498   // If mirror or obj is dead, only null-path is taken.
3499   if (stopped())  return true;
3500 
3501   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
3502 
3503   // Now load the mirror's klass metaobject, and null-check it.
3504   // Side-effects region with the control path if the klass is null.
3505   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
3506   // If kls is null, we have a primitive mirror.
3507   phi->init_req(_prim_path, prim_return_value);
3508   if (stopped()) { set_result(region, phi); return true; }
3509   bool safe_for_replace = (region->in(_prim_path) == top());
3510 
3511   Node* p;  // handy temp
3512   Node* null_ctl;
3513 
3514   // Now that we have the non-null klass, we can perform the real query.
3515   // For constant classes, the query will constant-fold in LoadNode::Value.
3516   Node* query_value = top();
3517   switch (id) {
3518   case vmIntrinsics::_isInstance:
3519     // nothing is an instance of a primitive type
3520     query_value = gen_instanceof(obj, kls, safe_for_replace);
3521     break;
3522 
3523   case vmIntrinsics::_getModifiers:
3524     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
3525     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3526     break;
3527 
3528   case vmIntrinsics::_isInterface:
3529     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3530     if (generate_interface_guard(kls, region) != NULL)
3531       // A guard was added.  If the guard is taken, it was an interface.
3532       phi->add_req(intcon(1));
3533     // If we fall through, it's a plain class.
3534     query_value = intcon(0);
3535     break;
3536 
3537   case vmIntrinsics::_isArray:
3538     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
3539     if (generate_array_guard(kls, region) != NULL)
3540       // A guard was added.  If the guard is taken, it was an array.
3541       phi->add_req(intcon(1));
3542     // If we fall through, it's a plain class.
3543     query_value = intcon(0);
3544     break;
3545 
3546   case vmIntrinsics::_isPrimitive:
3547     query_value = intcon(0); // "normal" path produces false
3548     break;
3549 
3550   case vmIntrinsics::_getSuperclass:
3551     // The rules here are somewhat unfortunate, but we can still do better
3552     // with random logic than with a JNI call.
3553     // Interfaces store null or Object as _super, but must report null.
3554     // Arrays store an intermediate super as _super, but must report Object.
3555     // Other types can report the actual _super.
3556     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3557     if (generate_interface_guard(kls, region) != NULL)
3558       // A guard was added.  If the guard is taken, it was an interface.
3559       phi->add_req(null());
3560     if (generate_array_guard(kls, region) != NULL)
3561       // A guard was added.  If the guard is taken, it was an array.
3562       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3563     // If we fall through, it's a plain class.  Get its _super.
3564     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3565     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3566     null_ctl = top();
3567     kls = null_check_oop(kls, &null_ctl);
3568     if (null_ctl != top()) {
3569       // If the guard is taken, Object.superClass is null (both klass and mirror).
3570       region->add_req(null_ctl);
3571       phi   ->add_req(null());
3572     }
3573     if (!stopped()) {
3574       query_value = load_mirror_from_klass(kls);
3575     }
3576     break;
3577 
3578   case vmIntrinsics::_getClassAccessFlags:
3579     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3580     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3581     break;
3582 
3583   default:
3584     fatal_unexpected_iid(id);
3585     break;
3586   }
3587 
3588   // Fall-through is the normal case of a query to a real class.
3589   phi->init_req(1, query_value);
3590   region->init_req(1, control());
3591 
3592   C->set_has_split_ifs(true); // Has chance for split-if optimization
3593   set_result(region, phi);
3594   return true;
3595 }
3596 
3597 //-------------------------inline_Class_cast-------------------
3598 bool LibraryCallKit::inline_Class_cast() {
3599   Node* mirror = argument(0); // Class
3600   Node* obj    = argument(1);
3601   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3602   if (mirror_con == NULL) {
3603     return false;  // dead path (mirror->is_top()).
3604   }
3605   if (obj == NULL || obj->is_top()) {
3606     return false;  // dead path
3607   }
3608   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3609 
3610   // First, see if Class.cast() can be folded statically.
3611   // java_mirror_type() returns non-null for compile-time Class constants.
3612   ciType* tm = mirror_con->java_mirror_type();
3613   if (tm != NULL && tm->is_klass() &&
3614       tp != NULL && tp->klass() != NULL) {
3615     if (!tp->klass()->is_loaded()) {
3616       // Don't use intrinsic when class is not loaded.
3617       return false;
3618     } else {
3619       int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3620       if (static_res == Compile::SSC_always_true) {
3621         // isInstance() is true - fold the code.
3622         set_result(obj);
3623         return true;
3624       } else if (static_res == Compile::SSC_always_false) {
3625         // Don't use intrinsic, have to throw ClassCastException.
3626         // If the reference is null, the non-intrinsic bytecode will
3627         // be optimized appropriately.
3628         return false;
3629       }
3630     }
3631   }
3632 
3633   // Bailout intrinsic and do normal inlining if exception path is frequent.
3634   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3635     return false;
3636   }
3637 
3638   // Generate dynamic checks.
3639   // Class.cast() is java implementation of _checkcast bytecode.
3640   // Do checkcast (Parse::do_checkcast()) optimizations here.
3641 
3642   mirror = null_check(mirror);
3643   // If mirror is dead, only null-path is taken.
3644   if (stopped()) {
3645     return true;
3646   }
3647 
3648   // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3649   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3650   RegionNode* region = new RegionNode(PATH_LIMIT);
3651   record_for_igvn(region);
3652 
3653   // Now load the mirror's klass metaobject, and null-check it.
3654   // If kls is null, we have a primitive mirror and
3655   // nothing is an instance of a primitive type.
3656   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3657 
3658   Node* res = top();
3659   if (!stopped()) {
3660     Node* bad_type_ctrl = top();
3661     // Do checkcast optimizations.
3662     res = gen_checkcast(obj, kls, &bad_type_ctrl);
3663     region->init_req(_bad_type_path, bad_type_ctrl);
3664   }
3665   if (region->in(_prim_path) != top() ||
3666       region->in(_bad_type_path) != top()) {
3667     // Let Interpreter throw ClassCastException.
3668     PreserveJVMState pjvms(this);
3669     set_control(_gvn.transform(region));
3670     uncommon_trap(Deoptimization::Reason_intrinsic,
3671                   Deoptimization::Action_maybe_recompile);
3672   }
3673   if (!stopped()) {
3674     set_result(res);
3675   }
3676   return true;
3677 }
3678 
3679 
3680 //--------------------------inline_native_subtype_check------------------------
3681 // This intrinsic takes the JNI calls out of the heart of
3682 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3683 bool LibraryCallKit::inline_native_subtype_check() {
3684   // Pull both arguments off the stack.
3685   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3686   args[0] = argument(0);
3687   args[1] = argument(1);
3688   Node* klasses[2];             // corresponding Klasses: superk, subk
3689   klasses[0] = klasses[1] = top();
3690 
3691   enum {
3692     // A full decision tree on {superc is prim, subc is prim}:
3693     _prim_0_path = 1,           // {P,N} => false
3694                                 // {P,P} & superc!=subc => false
3695     _prim_same_path,            // {P,P} & superc==subc => true
3696     _prim_1_path,               // {N,P} => false
3697     _ref_subtype_path,          // {N,N} & subtype check wins => true
3698     _both_ref_path,             // {N,N} & subtype check loses => false
3699     PATH_LIMIT
3700   };
3701 
3702   RegionNode* region = new RegionNode(PATH_LIMIT);
3703   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3704   record_for_igvn(region);
3705 
3706   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3707   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3708   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3709 
3710   // First null-check both mirrors and load each mirror's klass metaobject.
3711   int which_arg;
3712   for (which_arg = 0; which_arg <= 1; which_arg++) {
3713     Node* arg = args[which_arg];
3714     arg = null_check(arg);
3715     if (stopped())  break;
3716     args[which_arg] = arg;
3717 
3718     Node* p = basic_plus_adr(arg, class_klass_offset);
3719     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3720     klasses[which_arg] = _gvn.transform(kls);
3721   }
3722 
3723   // Having loaded both klasses, test each for null.
3724   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3725   for (which_arg = 0; which_arg <= 1; which_arg++) {
3726     Node* kls = klasses[which_arg];
3727     Node* null_ctl = top();
3728     kls = null_check_oop(kls, &null_ctl, never_see_null);
3729     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3730     region->init_req(prim_path, null_ctl);
3731     if (stopped())  break;
3732     klasses[which_arg] = kls;
3733   }
3734 
3735   if (!stopped()) {
3736     // now we have two reference types, in klasses[0..1]
3737     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3738     Node* superk = klasses[0];  // the receiver
3739     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3740     // now we have a successful reference subtype check
3741     region->set_req(_ref_subtype_path, control());
3742   }
3743 
3744   // If both operands are primitive (both klasses null), then
3745   // we must return true when they are identical primitives.
3746   // It is convenient to test this after the first null klass check.
3747   set_control(region->in(_prim_0_path)); // go back to first null check
3748   if (!stopped()) {
3749     // Since superc is primitive, make a guard for the superc==subc case.
3750     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3751     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3752     generate_guard(bol_eq, region, PROB_FAIR);
3753     if (region->req() == PATH_LIMIT+1) {
3754       // A guard was added.  If the added guard is taken, superc==subc.
3755       region->swap_edges(PATH_LIMIT, _prim_same_path);
3756       region->del_req(PATH_LIMIT);
3757     }
3758     region->set_req(_prim_0_path, control()); // Not equal after all.
3759   }
3760 
3761   // these are the only paths that produce 'true':
3762   phi->set_req(_prim_same_path,   intcon(1));
3763   phi->set_req(_ref_subtype_path, intcon(1));
3764 
3765   // pull together the cases:
3766   assert(region->req() == PATH_LIMIT, "sane region");
3767   for (uint i = 1; i < region->req(); i++) {
3768     Node* ctl = region->in(i);
3769     if (ctl == NULL || ctl == top()) {
3770       region->set_req(i, top());
3771       phi   ->set_req(i, top());
3772     } else if (phi->in(i) == NULL) {
3773       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3774     }
3775   }
3776 
3777   set_control(_gvn.transform(region));
3778   set_result(_gvn.transform(phi));
3779   return true;
3780 }
3781 
3782 //---------------------generate_array_guard_common------------------------
3783 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3784                                                   bool obj_array, bool not_array) {
3785 
3786   if (stopped()) {
3787     return NULL;
3788   }
3789 
3790   // If obj_array/non_array==false/false:
3791   // Branch around if the given klass is in fact an array (either obj or prim).
3792   // If obj_array/non_array==false/true:
3793   // Branch around if the given klass is not an array klass of any kind.
3794   // If obj_array/non_array==true/true:
3795   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3796   // If obj_array/non_array==true/false:
3797   // Branch around if the kls is an oop array (Object[] or subtype)
3798   //
3799   // Like generate_guard, adds a new path onto the region.
3800   jint  layout_con = 0;
3801   Node* layout_val = get_layout_helper(kls, layout_con);
3802   if (layout_val == NULL) {
3803     bool query = (obj_array
3804                   ? Klass::layout_helper_is_objArray(layout_con)
3805                   : Klass::layout_helper_is_array(layout_con));
3806     if (query == not_array) {
3807       return NULL;                       // never a branch
3808     } else {                             // always a branch
3809       Node* always_branch = control();
3810       if (region != NULL)
3811         region->add_req(always_branch);
3812       set_control(top());
3813       return always_branch;
3814     }
3815   }
3816   // Now test the correct condition.
3817   jint  nval = (obj_array
3818                 ? ((jint)Klass::_lh_array_tag_type_value
3819                    <<    Klass::_lh_array_tag_shift)
3820                 : Klass::_lh_neutral_value);
3821   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3822   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3823   // invert the test if we are looking for a non-array
3824   if (not_array)  btest = BoolTest(btest).negate();
3825   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3826   return generate_fair_guard(bol, region);
3827 }
3828 
3829 
3830 //-----------------------inline_native_newArray--------------------------
3831 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3832 bool LibraryCallKit::inline_native_newArray() {
3833   Node* mirror    = argument(0);
3834   Node* count_val = argument(1);
3835 
3836   mirror = null_check(mirror);
3837   // If mirror or obj is dead, only null-path is taken.
3838   if (stopped())  return true;
3839 
3840   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3841   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3842   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3843   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
3844   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3845 
3846   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3847   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3848                                                   result_reg, _slow_path);
3849   Node* normal_ctl   = control();
3850   Node* no_array_ctl = result_reg->in(_slow_path);
3851 
3852   // Generate code for the slow case.  We make a call to newArray().
3853   set_control(no_array_ctl);
3854   if (!stopped()) {
3855     // Either the input type is void.class, or else the
3856     // array klass has not yet been cached.  Either the
3857     // ensuing call will throw an exception, or else it
3858     // will cache the array klass for next time.
3859     PreserveJVMState pjvms(this);
3860     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3861     Node* slow_result = set_results_for_java_call(slow_call);
3862     // this->control() comes from set_results_for_java_call
3863     result_reg->set_req(_slow_path, control());
3864     result_val->set_req(_slow_path, slow_result);
3865     result_io ->set_req(_slow_path, i_o());
3866     result_mem->set_req(_slow_path, reset_memory());
3867   }
3868 
3869   set_control(normal_ctl);
3870   if (!stopped()) {
3871     // Normal case:  The array type has been cached in the java.lang.Class.
3872     // The following call works fine even if the array type is polymorphic.
3873     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3874     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
3875     result_reg->init_req(_normal_path, control());
3876     result_val->init_req(_normal_path, obj);
3877     result_io ->init_req(_normal_path, i_o());
3878     result_mem->init_req(_normal_path, reset_memory());
3879   }
3880 
3881   // Return the combined state.
3882   set_i_o(        _gvn.transform(result_io)  );
3883   set_all_memory( _gvn.transform(result_mem));
3884 
3885   C->set_has_split_ifs(true); // Has chance for split-if optimization
3886   set_result(result_reg, result_val);
3887   return true;
3888 }
3889 
3890 //----------------------inline_native_getLength--------------------------
3891 // public static native int java.lang.reflect.Array.getLength(Object array);
3892 bool LibraryCallKit::inline_native_getLength() {
3893   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3894 
3895   Node* array = null_check(argument(0));
3896   // If array is dead, only null-path is taken.
3897   if (stopped())  return true;
3898 
3899   // Deoptimize if it is a non-array.
3900   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3901 
3902   if (non_array != NULL) {
3903     PreserveJVMState pjvms(this);
3904     set_control(non_array);
3905     uncommon_trap(Deoptimization::Reason_intrinsic,
3906                   Deoptimization::Action_maybe_recompile);
3907   }
3908 
3909   // If control is dead, only non-array-path is taken.
3910   if (stopped())  return true;
3911 
3912   // The works fine even if the array type is polymorphic.
3913   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3914   Node* result = load_array_length(array);
3915 
3916   C->set_has_split_ifs(true);  // Has chance for split-if optimization
3917   set_result(result);
3918   return true;
3919 }
3920 
3921 //------------------------inline_array_copyOf----------------------------
3922 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
3923 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
3924 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3925   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3926 
3927   // Get the arguments.
3928   Node* original          = argument(0);
3929   Node* start             = is_copyOfRange? argument(1): intcon(0);
3930   Node* end               = is_copyOfRange? argument(2): argument(1);
3931   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3932 
3933   Node* newcopy = NULL;
3934 
3935   // Set the original stack and the reexecute bit for the interpreter to reexecute
3936   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3937   { PreserveReexecuteState preexecs(this);
3938     jvms()->set_should_reexecute(true);
3939 
3940     array_type_mirror = null_check(array_type_mirror);
3941     original          = null_check(original);
3942 
3943     // Check if a null path was taken unconditionally.
3944     if (stopped())  return true;
3945 
3946     Node* orig_length = load_array_length(original);
3947 
3948     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3949     klass_node = null_check(klass_node);
3950 
3951     RegionNode* bailout = new RegionNode(1);
3952     record_for_igvn(bailout);
3953 
3954     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3955     // Bail out if that is so.
3956     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3957     if (not_objArray != NULL) {
3958       // Improve the klass node's type from the new optimistic assumption:
3959       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3960       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3961       Node* cast = new CastPPNode(klass_node, akls);
3962       cast->init_req(0, control());
3963       klass_node = _gvn.transform(cast);
3964     }
3965 
3966     // Bail out if either start or end is negative.
3967     generate_negative_guard(start, bailout, &start);
3968     generate_negative_guard(end,   bailout, &end);
3969 
3970     Node* length = end;
3971     if (_gvn.type(start) != TypeInt::ZERO) {
3972       length = _gvn.transform(new SubINode(end, start));
3973     }
3974 
3975     // Bail out if length is negative.
3976     // Without this the new_array would throw
3977     // NegativeArraySizeException but IllegalArgumentException is what
3978     // should be thrown
3979     generate_negative_guard(length, bailout, &length);
3980 
3981     if (bailout->req() > 1) {
3982       PreserveJVMState pjvms(this);
3983       set_control(_gvn.transform(bailout));
3984       uncommon_trap(Deoptimization::Reason_intrinsic,
3985                     Deoptimization::Action_maybe_recompile);
3986     }
3987 
3988     if (!stopped()) {
3989       // How many elements will we copy from the original?
3990       // The answer is MinI(orig_length - start, length).
3991       Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3992       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3993 
3994       // Generate a direct call to the right arraycopy function(s).
3995       // We know the copy is disjoint but we might not know if the
3996       // oop stores need checking.
3997       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3998       // This will fail a store-check if x contains any non-nulls.
3999 
4000       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4001       // loads/stores but it is legal only if we're sure the
4002       // Arrays.copyOf would succeed. So we need all input arguments
4003       // to the copyOf to be validated, including that the copy to the
4004       // new array won't trigger an ArrayStoreException. That subtype
4005       // check can be optimized if we know something on the type of
4006       // the input array from type speculation.
4007       if (_gvn.type(klass_node)->singleton()) {
4008         ciKlass* subk   = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
4009         ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
4010 
4011         int test = C->static_subtype_check(superk, subk);
4012         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4013           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4014           if (t_original->speculative_type() != NULL) {
4015             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4016           }
4017         }
4018       }
4019 
4020       bool validated = false;
4021       // Reason_class_check rather than Reason_intrinsic because we
4022       // want to intrinsify even if this traps.
4023       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4024         Node* not_subtype_ctrl = gen_subtype_check(load_object_klass(original),
4025                                                    klass_node);
4026 
4027         if (not_subtype_ctrl != top()) {
4028           PreserveJVMState pjvms(this);
4029           set_control(not_subtype_ctrl);
4030           uncommon_trap(Deoptimization::Reason_class_check,
4031                         Deoptimization::Action_make_not_entrant);
4032           assert(stopped(), "Should be stopped");
4033         }
4034         validated = true;
4035       }
4036 
4037       if (!stopped()) {
4038         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4039 
4040         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true,
4041                                                 load_object_klass(original), klass_node);
4042         if (!is_copyOfRange) {
4043           ac->set_copyof(validated);
4044         } else {
4045           ac->set_copyofrange(validated);
4046         }
4047         Node* n = _gvn.transform(ac);
4048         if (n == ac) {
4049           ac->connect_outputs(this);
4050         } else {
4051           assert(validated, "shouldn't transform if all arguments not validated");
4052           set_all_memory(n);
4053         }
4054       }
4055     }
4056   } // original reexecute is set back here
4057 
4058   C->set_has_split_ifs(true); // Has chance for split-if optimization
4059   if (!stopped()) {
4060     set_result(newcopy);
4061   }
4062   return true;
4063 }
4064 
4065 
4066 //----------------------generate_virtual_guard---------------------------
4067 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
4068 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4069                                              RegionNode* slow_region) {
4070   ciMethod* method = callee();
4071   int vtable_index = method->vtable_index();
4072   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4073          "bad index %d", vtable_index);
4074   // Get the Method* out of the appropriate vtable entry.
4075   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
4076                      vtable_index*vtableEntry::size_in_bytes() +
4077                      vtableEntry::method_offset_in_bytes();
4078   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
4079   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4080 
4081   // Compare the target method with the expected method (e.g., Object.hashCode).
4082   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4083 
4084   Node* native_call = makecon(native_call_addr);
4085   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
4086   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4087 
4088   return generate_slow_guard(test_native, slow_region);
4089 }
4090 
4091 //-----------------------generate_method_call----------------------------
4092 // Use generate_method_call to make a slow-call to the real
4093 // method if the fast path fails.  An alternative would be to
4094 // use a stub like OptoRuntime::slow_arraycopy_Java.
4095 // This only works for expanding the current library call,
4096 // not another intrinsic.  (E.g., don't use this for making an
4097 // arraycopy call inside of the copyOf intrinsic.)
4098 CallJavaNode*
4099 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
4100   // When compiling the intrinsic method itself, do not use this technique.
4101   guarantee(callee() != C->method(), "cannot make slow-call to self");
4102 
4103   ciMethod* method = callee();
4104   // ensure the JVMS we have will be correct for this call
4105   guarantee(method_id == method->intrinsic_id(), "must match");
4106 
4107   const TypeFunc* tf = TypeFunc::make(method);
4108   CallJavaNode* slow_call;
4109   if (is_static) {
4110     assert(!is_virtual, "");
4111     slow_call = new CallStaticJavaNode(C, tf,
4112                            SharedRuntime::get_resolve_static_call_stub(),
4113                            method, bci());
4114   } else if (is_virtual) {
4115     null_check_receiver();
4116     int vtable_index = Method::invalid_vtable_index;
4117     if (UseInlineCaches) {
4118       // Suppress the vtable call
4119     } else {
4120       // hashCode and clone are not a miranda methods,
4121       // so the vtable index is fixed.
4122       // No need to use the linkResolver to get it.
4123        vtable_index = method->vtable_index();
4124        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4125               "bad index %d", vtable_index);
4126     }
4127     slow_call = new CallDynamicJavaNode(tf,
4128                           SharedRuntime::get_resolve_virtual_call_stub(),
4129                           method, vtable_index, bci());
4130   } else {  // neither virtual nor static:  opt_virtual
4131     null_check_receiver();
4132     slow_call = new CallStaticJavaNode(C, tf,
4133                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
4134                                 method, bci());
4135     slow_call->set_optimized_virtual(true);
4136   }
4137   set_arguments_for_java_call(slow_call);
4138   set_edges_for_java_call(slow_call);
4139   return slow_call;
4140 }
4141 
4142 
4143 /**
4144  * Build special case code for calls to hashCode on an object. This call may
4145  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4146  * slightly different code.
4147  */
4148 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4149   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4150   assert(!(is_virtual && is_static), "either virtual, special, or static");
4151 
4152   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4153 
4154   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4155   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4156   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4157   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4158   Node* obj = NULL;
4159   if (!is_static) {
4160     // Check for hashing null object
4161     obj = null_check_receiver();
4162     if (stopped())  return true;        // unconditionally null
4163     result_reg->init_req(_null_path, top());
4164     result_val->init_req(_null_path, top());
4165   } else {
4166     // Do a null check, and return zero if null.
4167     // System.identityHashCode(null) == 0
4168     obj = argument(0);
4169     Node* null_ctl = top();
4170     obj = null_check_oop(obj, &null_ctl);
4171     result_reg->init_req(_null_path, null_ctl);
4172     result_val->init_req(_null_path, _gvn.intcon(0));
4173   }
4174 
4175   // Unconditionally null?  Then return right away.
4176   if (stopped()) {
4177     set_control( result_reg->in(_null_path));
4178     if (!stopped())
4179       set_result(result_val->in(_null_path));
4180     return true;
4181   }
4182 
4183   // We only go to the fast case code if we pass a number of guards.  The
4184   // paths which do not pass are accumulated in the slow_region.
4185   RegionNode* slow_region = new RegionNode(1);
4186   record_for_igvn(slow_region);
4187 
4188   // If this is a virtual call, we generate a funny guard.  We pull out
4189   // the vtable entry corresponding to hashCode() from the target object.
4190   // If the target method which we are calling happens to be the native
4191   // Object hashCode() method, we pass the guard.  We do not need this
4192   // guard for non-virtual calls -- the caller is known to be the native
4193   // Object hashCode().
4194   if (is_virtual) {
4195     // After null check, get the object's klass.
4196     Node* obj_klass = load_object_klass(obj);
4197     generate_virtual_guard(obj_klass, slow_region);
4198   }
4199 
4200   // Get the header out of the object, use LoadMarkNode when available
4201   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4202   // The control of the load must be NULL. Otherwise, the load can move before
4203   // the null check after castPP removal.
4204   Node* no_ctrl = NULL;
4205   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4206 
4207   // Test the header to see if it is unlocked.
4208   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
4209   Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4210   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
4211   Node *chk_unlocked   = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
4212   Node *test_unlocked  = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
4213 
4214   generate_slow_guard(test_unlocked, slow_region);
4215 
4216   // Get the hash value and check to see that it has been properly assigned.
4217   // We depend on hash_mask being at most 32 bits and avoid the use of
4218   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4219   // vm: see markOop.hpp.
4220   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
4221   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
4222   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4223   // This hack lets the hash bits live anywhere in the mark object now, as long
4224   // as the shift drops the relevant bits into the low 32 bits.  Note that
4225   // Java spec says that HashCode is an int so there's no point in capturing
4226   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4227   hshifted_header      = ConvX2I(hshifted_header);
4228   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4229 
4230   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
4231   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4232   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4233 
4234   generate_slow_guard(test_assigned, slow_region);
4235 
4236   Node* init_mem = reset_memory();
4237   // fill in the rest of the null path:
4238   result_io ->init_req(_null_path, i_o());
4239   result_mem->init_req(_null_path, init_mem);
4240 
4241   result_val->init_req(_fast_path, hash_val);
4242   result_reg->init_req(_fast_path, control());
4243   result_io ->init_req(_fast_path, i_o());
4244   result_mem->init_req(_fast_path, init_mem);
4245 
4246   // Generate code for the slow case.  We make a call to hashCode().
4247   set_control(_gvn.transform(slow_region));
4248   if (!stopped()) {
4249     // No need for PreserveJVMState, because we're using up the present state.
4250     set_all_memory(init_mem);
4251     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4252     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
4253     Node* slow_result = set_results_for_java_call(slow_call);
4254     // this->control() comes from set_results_for_java_call
4255     result_reg->init_req(_slow_path, control());
4256     result_val->init_req(_slow_path, slow_result);
4257     result_io  ->set_req(_slow_path, i_o());
4258     result_mem ->set_req(_slow_path, reset_memory());
4259   }
4260 
4261   // Return the combined state.
4262   set_i_o(        _gvn.transform(result_io)  );
4263   set_all_memory( _gvn.transform(result_mem));
4264 
4265   set_result(result_reg, result_val);
4266   return true;
4267 }
4268 
4269 //---------------------------inline_native_getClass----------------------------
4270 // public final native Class<?> java.lang.Object.getClass();
4271 //
4272 // Build special case code for calls to getClass on an object.
4273 bool LibraryCallKit::inline_native_getClass() {
4274   Node* obj = null_check_receiver();
4275   if (stopped())  return true;
4276   set_result(load_mirror_from_klass(load_object_klass(obj)));
4277   return true;
4278 }
4279 
4280 //-----------------inline_native_Reflection_getCallerClass---------------------
4281 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4282 //
4283 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4284 //
4285 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4286 // in that it must skip particular security frames and checks for
4287 // caller sensitive methods.
4288 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4289 #ifndef PRODUCT
4290   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4291     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4292   }
4293 #endif
4294 
4295   if (!jvms()->has_method()) {
4296 #ifndef PRODUCT
4297     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4298       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
4299     }
4300 #endif
4301     return false;
4302   }
4303 
4304   // Walk back up the JVM state to find the caller at the required
4305   // depth.
4306   JVMState* caller_jvms = jvms();
4307 
4308   // Cf. JVM_GetCallerClass
4309   // NOTE: Start the loop at depth 1 because the current JVM state does
4310   // not include the Reflection.getCallerClass() frame.
4311   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
4312     ciMethod* m = caller_jvms->method();
4313     switch (n) {
4314     case 0:
4315       fatal("current JVM state does not include the Reflection.getCallerClass frame");
4316       break;
4317     case 1:
4318       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4319       if (!m->caller_sensitive()) {
4320 #ifndef PRODUCT
4321         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4322           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
4323         }
4324 #endif
4325         return false;  // bail-out; let JVM_GetCallerClass do the work
4326       }
4327       break;
4328     default:
4329       if (!m->is_ignored_by_security_stack_walk()) {
4330         // We have reached the desired frame; return the holder class.
4331         // Acquire method holder as java.lang.Class and push as constant.
4332         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4333         ciInstance* caller_mirror = caller_klass->java_mirror();
4334         set_result(makecon(TypeInstPtr::make(caller_mirror)));
4335 
4336 #ifndef PRODUCT
4337         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4338           tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
4339           tty->print_cr("  JVM state at this point:");
4340           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4341             ciMethod* m = jvms()->of_depth(i)->method();
4342             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4343           }
4344         }
4345 #endif
4346         return true;
4347       }
4348       break;
4349     }
4350   }
4351 
4352 #ifndef PRODUCT
4353   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4354     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4355     tty->print_cr("  JVM state at this point:");
4356     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4357       ciMethod* m = jvms()->of_depth(i)->method();
4358       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4359     }
4360   }
4361 #endif
4362 
4363   return false;  // bail-out; let JVM_GetCallerClass do the work
4364 }
4365 
4366 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
4367   Node* arg = argument(0);
4368   Node* result = NULL;
4369 
4370   switch (id) {
4371   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
4372   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
4373   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
4374   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
4375 
4376   case vmIntrinsics::_doubleToLongBits: {
4377     // two paths (plus control) merge in a wood
4378     RegionNode *r = new RegionNode(3);
4379     Node *phi = new PhiNode(r, TypeLong::LONG);
4380 
4381     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
4382     // Build the boolean node
4383     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4384 
4385     // Branch either way.
4386     // NaN case is less traveled, which makes all the difference.
4387     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4388     Node *opt_isnan = _gvn.transform(ifisnan);
4389     assert( opt_isnan->is_If(), "Expect an IfNode");
4390     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4391     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4392 
4393     set_control(iftrue);
4394 
4395     static const jlong nan_bits = CONST64(0x7ff8000000000000);
4396     Node *slow_result = longcon(nan_bits); // return NaN
4397     phi->init_req(1, _gvn.transform( slow_result ));
4398     r->init_req(1, iftrue);
4399 
4400     // Else fall through
4401     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4402     set_control(iffalse);
4403 
4404     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
4405     r->init_req(2, iffalse);
4406 
4407     // Post merge
4408     set_control(_gvn.transform(r));
4409     record_for_igvn(r);
4410 
4411     C->set_has_split_ifs(true); // Has chance for split-if optimization
4412     result = phi;
4413     assert(result->bottom_type()->isa_long(), "must be");
4414     break;
4415   }
4416 
4417   case vmIntrinsics::_floatToIntBits: {
4418     // two paths (plus control) merge in a wood
4419     RegionNode *r = new RegionNode(3);
4420     Node *phi = new PhiNode(r, TypeInt::INT);
4421 
4422     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
4423     // Build the boolean node
4424     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
4425 
4426     // Branch either way.
4427     // NaN case is less traveled, which makes all the difference.
4428     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
4429     Node *opt_isnan = _gvn.transform(ifisnan);
4430     assert( opt_isnan->is_If(), "Expect an IfNode");
4431     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
4432     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
4433 
4434     set_control(iftrue);
4435 
4436     static const jint nan_bits = 0x7fc00000;
4437     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
4438     phi->init_req(1, _gvn.transform( slow_result ));
4439     r->init_req(1, iftrue);
4440 
4441     // Else fall through
4442     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
4443     set_control(iffalse);
4444 
4445     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
4446     r->init_req(2, iffalse);
4447 
4448     // Post merge
4449     set_control(_gvn.transform(r));
4450     record_for_igvn(r);
4451 
4452     C->set_has_split_ifs(true); // Has chance for split-if optimization
4453     result = phi;
4454     assert(result->bottom_type()->isa_int(), "must be");
4455     break;
4456   }
4457 
4458   default:
4459     fatal_unexpected_iid(id);
4460     break;
4461   }
4462   set_result(_gvn.transform(result));
4463   return true;
4464 }
4465 
4466 //----------------------inline_unsafe_copyMemory-------------------------
4467 // public native void Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
4468 bool LibraryCallKit::inline_unsafe_copyMemory() {
4469   if (callee()->is_static())  return false;  // caller must have the capability!
4470   null_check_receiver();  // null-check receiver
4471   if (stopped())  return true;
4472 
4473   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
4474 
4475   Node* src_ptr =         argument(1);   // type: oop
4476   Node* src_off = ConvL2X(argument(2));  // type: long
4477   Node* dst_ptr =         argument(4);   // type: oop
4478   Node* dst_off = ConvL2X(argument(5));  // type: long
4479   Node* size    = ConvL2X(argument(7));  // type: long
4480 
4481   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4482          "fieldOffset must be byte-scaled");
4483 
4484   Node* src = make_unsafe_address(src_ptr, src_off);
4485   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4486 
4487   // Conservatively insert a memory barrier on all memory slices.
4488   // Do not let writes of the copy source or destination float below the copy.
4489   insert_mem_bar(Op_MemBarCPUOrder);
4490 
4491   // Call it.  Note that the length argument is not scaled.
4492   make_runtime_call(RC_LEAF|RC_NO_FP,
4493                     OptoRuntime::fast_arraycopy_Type(),
4494                     StubRoutines::unsafe_arraycopy(),
4495                     "unsafe_arraycopy",
4496                     TypeRawPtr::BOTTOM,
4497                     src, dst, size XTOP);
4498 
4499   // Do not let reads of the copy destination float above the copy.
4500   insert_mem_bar(Op_MemBarCPUOrder);
4501 
4502   return true;
4503 }
4504 
4505 //------------------------clone_coping-----------------------------------
4506 // Helper function for inline_native_clone.
4507 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4508   assert(obj_size != NULL, "");
4509   Node* raw_obj = alloc_obj->in(1);
4510   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4511 
4512   AllocateNode* alloc = NULL;
4513   if (ReduceBulkZeroing) {
4514     // We will be completely responsible for initializing this object -
4515     // mark Initialize node as complete.
4516     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4517     // The object was just allocated - there should be no any stores!
4518     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4519     // Mark as complete_with_arraycopy so that on AllocateNode
4520     // expansion, we know this AllocateNode is initialized by an array
4521     // copy and a StoreStore barrier exists after the array copy.
4522     alloc->initialization()->set_complete_with_arraycopy();
4523   }
4524 
4525   // Copy the fastest available way.
4526   // TODO: generate fields copies for small objects instead.
4527   Node* src  = obj;
4528   Node* dest = alloc_obj;
4529   Node* size = _gvn.transform(obj_size);
4530 
4531   // Exclude the header but include array length to copy by 8 bytes words.
4532   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4533   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4534                             instanceOopDesc::base_offset_in_bytes();
4535   // base_off:
4536   // 8  - 32-bit VM
4537   // 12 - 64-bit VM, compressed klass
4538   // 16 - 64-bit VM, normal klass
4539   if (base_off % BytesPerLong != 0) {
4540     assert(UseCompressedClassPointers, "");
4541     if (is_array) {
4542       // Exclude length to copy by 8 bytes words.
4543       base_off += sizeof(int);
4544     } else {
4545       // Include klass to copy by 8 bytes words.
4546       base_off = instanceOopDesc::klass_offset_in_bytes();
4547     }
4548     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4549   }
4550   src  = basic_plus_adr(src,  base_off);
4551   dest = basic_plus_adr(dest, base_off);
4552 
4553   // Compute the length also, if needed:
4554   Node* countx = size;
4555   countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
4556   countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong) ));
4557 
4558   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4559 
4560   ArrayCopyNode* ac = ArrayCopyNode::make(this, false, src, NULL, dest, NULL, countx, false);
4561   ac->set_clonebasic();
4562   Node* n = _gvn.transform(ac);
4563   if (n == ac) {
4564     set_predefined_output_for_runtime_call(ac, ac->in(TypeFunc::Memory), raw_adr_type);
4565   } else {
4566     set_all_memory(n);
4567   }
4568 
4569   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4570   if (card_mark) {
4571     assert(!is_array, "");
4572     // Put in store barrier for any and all oops we are sticking
4573     // into this object.  (We could avoid this if we could prove
4574     // that the object type contains no oop fields at all.)
4575     Node* no_particular_value = NULL;
4576     Node* no_particular_field = NULL;
4577     int raw_adr_idx = Compile::AliasIdxRaw;
4578     post_barrier(control(),
4579                  memory(raw_adr_type),
4580                  alloc_obj,
4581                  no_particular_field,
4582                  raw_adr_idx,
4583                  no_particular_value,
4584                  T_OBJECT,
4585                  false);
4586   }
4587 
4588   // Do not let reads from the cloned object float above the arraycopy.
4589   if (alloc != NULL) {
4590     // Do not let stores that initialize this object be reordered with
4591     // a subsequent store that would make this object accessible by
4592     // other threads.
4593     // Record what AllocateNode this StoreStore protects so that
4594     // escape analysis can go from the MemBarStoreStoreNode to the
4595     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4596     // based on the escape status of the AllocateNode.
4597     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
4598   } else {
4599     insert_mem_bar(Op_MemBarCPUOrder);
4600   }
4601 }
4602 
4603 //------------------------inline_native_clone----------------------------
4604 // protected native Object java.lang.Object.clone();
4605 //
4606 // Here are the simple edge cases:
4607 //  null receiver => normal trap
4608 //  virtual and clone was overridden => slow path to out-of-line clone
4609 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4610 //
4611 // The general case has two steps, allocation and copying.
4612 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4613 //
4614 // Copying also has two cases, oop arrays and everything else.
4615 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4616 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4617 //
4618 // These steps fold up nicely if and when the cloned object's klass
4619 // can be sharply typed as an object array, a type array, or an instance.
4620 //
4621 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4622   PhiNode* result_val;
4623 
4624   // Set the reexecute bit for the interpreter to reexecute
4625   // the bytecode that invokes Object.clone if deoptimization happens.
4626   { PreserveReexecuteState preexecs(this);
4627     jvms()->set_should_reexecute(true);
4628 
4629     Node* obj = null_check_receiver();
4630     if (stopped())  return true;
4631 
4632     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4633 
4634     // If we are going to clone an instance, we need its exact type to
4635     // know the number and types of fields to convert the clone to
4636     // loads/stores. Maybe a speculative type can help us.
4637     if (!obj_type->klass_is_exact() &&
4638         obj_type->speculative_type() != NULL &&
4639         obj_type->speculative_type()->is_instance_klass()) {
4640       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4641       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4642           !spec_ik->has_injected_fields()) {
4643         ciKlass* k = obj_type->klass();
4644         if (!k->is_instance_klass() ||
4645             k->as_instance_klass()->is_interface() ||
4646             k->as_instance_klass()->has_subklass()) {
4647           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4648         }
4649       }
4650     }
4651 
4652     Node* obj_klass = load_object_klass(obj);
4653     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4654     const TypeOopPtr*   toop   = ((tklass != NULL)
4655                                 ? tklass->as_instance_type()
4656                                 : TypeInstPtr::NOTNULL);
4657 
4658     // Conservatively insert a memory barrier on all memory slices.
4659     // Do not let writes into the original float below the clone.
4660     insert_mem_bar(Op_MemBarCPUOrder);
4661 
4662     // paths into result_reg:
4663     enum {
4664       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4665       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4666       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4667       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4668       PATH_LIMIT
4669     };
4670     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4671     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4672     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
4673     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4674     record_for_igvn(result_reg);
4675 
4676     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4677     int raw_adr_idx = Compile::AliasIdxRaw;
4678 
4679     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4680     if (array_ctl != NULL) {
4681       // It's an array.
4682       PreserveJVMState pjvms(this);
4683       set_control(array_ctl);
4684       Node* obj_length = load_array_length(obj);
4685       Node* obj_size  = NULL;
4686       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
4687 
4688       if (!use_ReduceInitialCardMarks()) {
4689         // If it is an oop array, it requires very special treatment,
4690         // because card marking is required on each card of the array.
4691         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4692         if (is_obja != NULL) {
4693           PreserveJVMState pjvms2(this);
4694           set_control(is_obja);
4695           // Generate a direct call to the right arraycopy function(s).
4696           Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4697           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL);
4698           ac->set_cloneoop();
4699           Node* n = _gvn.transform(ac);
4700           assert(n == ac, "cannot disappear");
4701           ac->connect_outputs(this);
4702 
4703           result_reg->init_req(_objArray_path, control());
4704           result_val->init_req(_objArray_path, alloc_obj);
4705           result_i_o ->set_req(_objArray_path, i_o());
4706           result_mem ->set_req(_objArray_path, reset_memory());
4707         }
4708       }
4709       // Otherwise, there are no card marks to worry about.
4710       // (We can dispense with card marks if we know the allocation
4711       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4712       //  causes the non-eden paths to take compensating steps to
4713       //  simulate a fresh allocation, so that no further
4714       //  card marks are required in compiled code to initialize
4715       //  the object.)
4716 
4717       if (!stopped()) {
4718         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4719 
4720         // Present the results of the copy.
4721         result_reg->init_req(_array_path, control());
4722         result_val->init_req(_array_path, alloc_obj);
4723         result_i_o ->set_req(_array_path, i_o());
4724         result_mem ->set_req(_array_path, reset_memory());
4725       }
4726     }
4727 
4728     // We only go to the instance fast case code if we pass a number of guards.
4729     // The paths which do not pass are accumulated in the slow_region.
4730     RegionNode* slow_region = new RegionNode(1);
4731     record_for_igvn(slow_region);
4732     if (!stopped()) {
4733       // It's an instance (we did array above).  Make the slow-path tests.
4734       // If this is a virtual call, we generate a funny guard.  We grab
4735       // the vtable entry corresponding to clone() from the target object.
4736       // If the target method which we are calling happens to be the
4737       // Object clone() method, we pass the guard.  We do not need this
4738       // guard for non-virtual calls; the caller is known to be the native
4739       // Object clone().
4740       if (is_virtual) {
4741         generate_virtual_guard(obj_klass, slow_region);
4742       }
4743 
4744       // The object must be easily cloneable and must not have a finalizer.
4745       // Both of these conditions may be checked in a single test.
4746       // We could optimize the test further, but we don't care.
4747       generate_access_flags_guard(obj_klass,
4748                                   // Test both conditions:
4749                                   JVM_ACC_IS_CLONEABLE_FAST | JVM_ACC_HAS_FINALIZER,
4750                                   // Must be cloneable but not finalizer:
4751                                   JVM_ACC_IS_CLONEABLE_FAST,
4752                                   slow_region);
4753     }
4754 
4755     if (!stopped()) {
4756       // It's an instance, and it passed the slow-path tests.
4757       PreserveJVMState pjvms(this);
4758       Node* obj_size  = NULL;
4759       // Need to deoptimize on exception from allocation since Object.clone intrinsic
4760       // is reexecuted if deoptimization occurs and there could be problems when merging
4761       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4762       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4763 
4764       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4765 
4766       // Present the results of the slow call.
4767       result_reg->init_req(_instance_path, control());
4768       result_val->init_req(_instance_path, alloc_obj);
4769       result_i_o ->set_req(_instance_path, i_o());
4770       result_mem ->set_req(_instance_path, reset_memory());
4771     }
4772 
4773     // Generate code for the slow case.  We make a call to clone().
4774     set_control(_gvn.transform(slow_region));
4775     if (!stopped()) {
4776       PreserveJVMState pjvms(this);
4777       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4778       Node* slow_result = set_results_for_java_call(slow_call);
4779       // this->control() comes from set_results_for_java_call
4780       result_reg->init_req(_slow_path, control());
4781       result_val->init_req(_slow_path, slow_result);
4782       result_i_o ->set_req(_slow_path, i_o());
4783       result_mem ->set_req(_slow_path, reset_memory());
4784     }
4785 
4786     // Return the combined state.
4787     set_control(    _gvn.transform(result_reg));
4788     set_i_o(        _gvn.transform(result_i_o));
4789     set_all_memory( _gvn.transform(result_mem));
4790   } // original reexecute is set back here
4791 
4792   set_result(_gvn.transform(result_val));
4793   return true;
4794 }
4795 
4796 // If we have a tighly coupled allocation, the arraycopy may take care
4797 // of the array initialization. If one of the guards we insert between
4798 // the allocation and the arraycopy causes a deoptimization, an
4799 // unitialized array will escape the compiled method. To prevent that
4800 // we set the JVM state for uncommon traps between the allocation and
4801 // the arraycopy to the state before the allocation so, in case of
4802 // deoptimization, we'll reexecute the allocation and the
4803 // initialization.
4804 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4805   if (alloc != NULL) {
4806     ciMethod* trap_method = alloc->jvms()->method();
4807     int trap_bci = alloc->jvms()->bci();
4808 
4809     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &
4810           !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4811       // Make sure there's no store between the allocation and the
4812       // arraycopy otherwise visible side effects could be rexecuted
4813       // in case of deoptimization and cause incorrect execution.
4814       bool no_interfering_store = true;
4815       Node* mem = alloc->in(TypeFunc::Memory);
4816       if (mem->is_MergeMem()) {
4817         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4818           Node* n = mms.memory();
4819           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4820             assert(n->is_Store(), "what else?");
4821             no_interfering_store = false;
4822             break;
4823           }
4824         }
4825       } else {
4826         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4827           Node* n = mms.memory();
4828           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4829             assert(n->is_Store(), "what else?");
4830             no_interfering_store = false;
4831             break;
4832           }
4833         }
4834       }
4835 
4836       if (no_interfering_store) {
4837         JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4838         uint size = alloc->req();
4839         SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4840         old_jvms->set_map(sfpt);
4841         for (uint i = 0; i < size; i++) {
4842           sfpt->init_req(i, alloc->in(i));
4843         }
4844         // re-push array length for deoptimization
4845         sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4846         old_jvms->set_sp(old_jvms->sp()+1);
4847         old_jvms->set_monoff(old_jvms->monoff()+1);
4848         old_jvms->set_scloff(old_jvms->scloff()+1);
4849         old_jvms->set_endoff(old_jvms->endoff()+1);
4850         old_jvms->set_should_reexecute(true);
4851 
4852         sfpt->set_i_o(map()->i_o());
4853         sfpt->set_memory(map()->memory());
4854         sfpt->set_control(map()->control());
4855 
4856         JVMState* saved_jvms = jvms();
4857         saved_reexecute_sp = _reexecute_sp;
4858 
4859         set_jvms(sfpt->jvms());
4860         _reexecute_sp = jvms()->sp();
4861 
4862         return saved_jvms;
4863       }
4864     }
4865   }
4866   return NULL;
4867 }
4868 
4869 // In case of a deoptimization, we restart execution at the
4870 // allocation, allocating a new array. We would leave an uninitialized
4871 // array in the heap that GCs wouldn't expect. Move the allocation
4872 // after the traps so we don't allocate the array if we
4873 // deoptimize. This is possible because tightly_coupled_allocation()
4874 // guarantees there's no observer of the allocated array at this point
4875 // and the control flow is simple enough.
4876 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms, int saved_reexecute_sp) {
4877   if (saved_jvms != NULL && !stopped()) {
4878     assert(alloc != NULL, "only with a tightly coupled allocation");
4879     // restore JVM state to the state at the arraycopy
4880     saved_jvms->map()->set_control(map()->control());
4881     assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4882     assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4883     // If we've improved the types of some nodes (null check) while
4884     // emitting the guards, propagate them to the current state
4885     map()->replaced_nodes().apply(saved_jvms->map());
4886     set_jvms(saved_jvms);
4887     _reexecute_sp = saved_reexecute_sp;
4888 
4889     // Remove the allocation from above the guards
4890     CallProjections callprojs;
4891     alloc->extract_projections(&callprojs, true);
4892     InitializeNode* init = alloc->initialization();
4893     Node* alloc_mem = alloc->in(TypeFunc::Memory);
4894     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4895     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4896     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4897 
4898     // move the allocation here (after the guards)
4899     _gvn.hash_delete(alloc);
4900     alloc->set_req(TypeFunc::Control, control());
4901     alloc->set_req(TypeFunc::I_O, i_o());
4902     Node *mem = reset_memory();
4903     set_all_memory(mem);
4904     alloc->set_req(TypeFunc::Memory, mem);
4905     set_control(init->proj_out(TypeFunc::Control));
4906     set_i_o(callprojs.fallthrough_ioproj);
4907 
4908     // Update memory as done in GraphKit::set_output_for_allocation()
4909     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4910     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4911     if (ary_type->isa_aryptr() && length_type != NULL) {
4912       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4913     }
4914     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4915     int            elemidx  = C->get_alias_index(telemref);
4916     set_memory(init->proj_out(TypeFunc::Memory), Compile::AliasIdxRaw);
4917     set_memory(init->proj_out(TypeFunc::Memory), elemidx);
4918 
4919     Node* allocx = _gvn.transform(alloc);
4920     assert(allocx == alloc, "where has the allocation gone?");
4921     assert(dest->is_CheckCastPP(), "not an allocation result?");
4922 
4923     _gvn.hash_delete(dest);
4924     dest->set_req(0, control());
4925     Node* destx = _gvn.transform(dest);
4926     assert(destx == dest, "where has the allocation result gone?");
4927   }
4928 }
4929 
4930 
4931 //------------------------------inline_arraycopy-----------------------
4932 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
4933 //                                                      Object dest, int destPos,
4934 //                                                      int length);
4935 bool LibraryCallKit::inline_arraycopy() {
4936   // Get the arguments.
4937   Node* src         = argument(0);  // type: oop
4938   Node* src_offset  = argument(1);  // type: int
4939   Node* dest        = argument(2);  // type: oop
4940   Node* dest_offset = argument(3);  // type: int
4941   Node* length      = argument(4);  // type: int
4942 
4943 
4944   // Check for allocation before we add nodes that would confuse
4945   // tightly_coupled_allocation()
4946   AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4947 
4948   int saved_reexecute_sp = -1;
4949   JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4950   // See arraycopy_restore_alloc_state() comment
4951   // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4952   // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4953   // if saved_jvms == NULL and alloc != NULL, we can’t emit any guards
4954   bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4955 
4956   // The following tests must be performed
4957   // (1) src and dest are arrays.
4958   // (2) src and dest arrays must have elements of the same BasicType
4959   // (3) src and dest must not be null.
4960   // (4) src_offset must not be negative.
4961   // (5) dest_offset must not be negative.
4962   // (6) length must not be negative.
4963   // (7) src_offset + length must not exceed length of src.
4964   // (8) dest_offset + length must not exceed length of dest.
4965   // (9) each element of an oop array must be assignable
4966 
4967   // (3) src and dest must not be null.
4968   // always do this here because we need the JVM state for uncommon traps
4969   Node* null_ctl = top();
4970   src  = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src,  T_ARRAY);
4971   assert(null_ctl->is_top(), "no null control here");
4972   dest = null_check(dest, T_ARRAY);
4973 
4974   if (!can_emit_guards) {
4975     // if saved_jvms == NULL and alloc != NULL, we don't emit any
4976     // guards but the arraycopy node could still take advantage of a
4977     // tightly allocated allocation. tightly_coupled_allocation() is
4978     // called again to make sure it takes the null check above into
4979     // account: the null check is mandatory and if it caused an
4980     // uncommon trap to be emitted then the allocation can't be
4981     // considered tightly coupled in this context.
4982     alloc = tightly_coupled_allocation(dest, NULL);
4983   }
4984 
4985   bool validated = false;
4986 
4987   const Type* src_type  = _gvn.type(src);
4988   const Type* dest_type = _gvn.type(dest);
4989   const TypeAryPtr* top_src  = src_type->isa_aryptr();
4990   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4991 
4992   // Do we have the type of src?
4993   bool has_src = (top_src != NULL && top_src->klass() != NULL);
4994   // Do we have the type of dest?
4995   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4996   // Is the type for src from speculation?
4997   bool src_spec = false;
4998   // Is the type for dest from speculation?
4999   bool dest_spec = false;
5000 
5001   if ((!has_src || !has_dest) && can_emit_guards) {
5002     // We don't have sufficient type information, let's see if
5003     // speculative types can help. We need to have types for both src
5004     // and dest so that it pays off.
5005 
5006     // Do we already have or could we have type information for src
5007     bool could_have_src = has_src;
5008     // Do we already have or could we have type information for dest
5009     bool could_have_dest = has_dest;
5010 
5011     ciKlass* src_k = NULL;
5012     if (!has_src) {
5013       src_k = src_type->speculative_type_not_null();
5014       if (src_k != NULL && src_k->is_array_klass()) {
5015         could_have_src = true;
5016       }
5017     }
5018 
5019     ciKlass* dest_k = NULL;
5020     if (!has_dest) {
5021       dest_k = dest_type->speculative_type_not_null();
5022       if (dest_k != NULL && dest_k->is_array_klass()) {
5023         could_have_dest = true;
5024       }
5025     }
5026 
5027     if (could_have_src && could_have_dest) {
5028       // This is going to pay off so emit the required guards
5029       if (!has_src) {
5030         src = maybe_cast_profiled_obj(src, src_k, true);
5031         src_type  = _gvn.type(src);
5032         top_src  = src_type->isa_aryptr();
5033         has_src = (top_src != NULL && top_src->klass() != NULL);
5034         src_spec = true;
5035       }
5036       if (!has_dest) {
5037         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5038         dest_type  = _gvn.type(dest);
5039         top_dest  = dest_type->isa_aryptr();
5040         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
5041         dest_spec = true;
5042       }
5043     }
5044   }
5045 
5046   if (has_src && has_dest && can_emit_guards) {
5047     BasicType src_elem  = top_src->klass()->as_array_klass()->element_type()->basic_type();
5048     BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
5049     if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
5050     if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
5051 
5052     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5053       // If both arrays are object arrays then having the exact types
5054       // for both will remove the need for a subtype check at runtime
5055       // before the call and may make it possible to pick a faster copy
5056       // routine (without a subtype check on every element)
5057       // Do we have the exact type of src?
5058       bool could_have_src = src_spec;
5059       // Do we have the exact type of dest?
5060       bool could_have_dest = dest_spec;
5061       ciKlass* src_k = top_src->klass();
5062       ciKlass* dest_k = top_dest->klass();
5063       if (!src_spec) {
5064         src_k = src_type->speculative_type_not_null();
5065         if (src_k != NULL && src_k->is_array_klass()) {
5066           could_have_src = true;
5067         }
5068       }
5069       if (!dest_spec) {
5070         dest_k = dest_type->speculative_type_not_null();
5071         if (dest_k != NULL && dest_k->is_array_klass()) {
5072           could_have_dest = true;
5073         }
5074       }
5075       if (could_have_src && could_have_dest) {
5076         // If we can have both exact types, emit the missing guards
5077         if (could_have_src && !src_spec) {
5078           src = maybe_cast_profiled_obj(src, src_k, true);
5079         }
5080         if (could_have_dest && !dest_spec) {
5081           dest = maybe_cast_profiled_obj(dest, dest_k, true);
5082         }
5083       }
5084     }
5085   }
5086 
5087   ciMethod* trap_method = method();
5088   int trap_bci = bci();
5089   if (saved_jvms != NULL) {
5090     trap_method = alloc->jvms()->method();
5091     trap_bci = alloc->jvms()->bci();
5092   }
5093 
5094   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5095       can_emit_guards &&
5096       !src->is_top() && !dest->is_top()) {
5097     // validate arguments: enables transformation the ArrayCopyNode
5098     validated = true;
5099 
5100     RegionNode* slow_region = new RegionNode(1);
5101     record_for_igvn(slow_region);
5102 
5103     // (1) src and dest are arrays.
5104     generate_non_array_guard(load_object_klass(src), slow_region);
5105     generate_non_array_guard(load_object_klass(dest), slow_region);
5106 
5107     // (2) src and dest arrays must have elements of the same BasicType
5108     // done at macro expansion or at Ideal transformation time
5109 
5110     // (4) src_offset must not be negative.
5111     generate_negative_guard(src_offset, slow_region);
5112 
5113     // (5) dest_offset must not be negative.
5114     generate_negative_guard(dest_offset, slow_region);
5115 
5116     // (7) src_offset + length must not exceed length of src.
5117     generate_limit_guard(src_offset, length,
5118                          load_array_length(src),
5119                          slow_region);
5120 
5121     // (8) dest_offset + length must not exceed length of dest.
5122     generate_limit_guard(dest_offset, length,
5123                          load_array_length(dest),
5124                          slow_region);
5125 
5126     // (9) each element of an oop array must be assignable
5127     Node* src_klass  = load_object_klass(src);
5128     Node* dest_klass = load_object_klass(dest);
5129     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
5130 
5131     if (not_subtype_ctrl != top()) {
5132       PreserveJVMState pjvms(this);
5133       set_control(not_subtype_ctrl);
5134       uncommon_trap(Deoptimization::Reason_intrinsic,
5135                     Deoptimization::Action_make_not_entrant);
5136       assert(stopped(), "Should be stopped");
5137     }
5138     {
5139       PreserveJVMState pjvms(this);
5140       set_control(_gvn.transform(slow_region));
5141       uncommon_trap(Deoptimization::Reason_intrinsic,
5142                     Deoptimization::Action_make_not_entrant);
5143       assert(stopped(), "Should be stopped");
5144     }
5145   }
5146 
5147   arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp);
5148 
5149   if (stopped()) {
5150     return true;
5151   }
5152 
5153   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL,
5154                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
5155                                           // so the compiler has a chance to eliminate them: during macro expansion,
5156                                           // we have to set their control (CastPP nodes are eliminated).
5157                                           load_object_klass(src), load_object_klass(dest),
5158                                           load_array_length(src), load_array_length(dest));
5159 
5160   ac->set_arraycopy(validated);
5161 
5162   Node* n = _gvn.transform(ac);
5163   if (n == ac) {
5164     ac->connect_outputs(this);
5165   } else {
5166     assert(validated, "shouldn't transform if all arguments not validated");
5167     set_all_memory(n);
5168   }
5169 
5170   return true;
5171 }
5172 
5173 
5174 // Helper function which determines if an arraycopy immediately follows
5175 // an allocation, with no intervening tests or other escapes for the object.
5176 AllocateArrayNode*
5177 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
5178                                            RegionNode* slow_region) {
5179   if (stopped())             return NULL;  // no fast path
5180   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
5181 
5182   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
5183   if (alloc == NULL)  return NULL;
5184 
5185   Node* rawmem = memory(Compile::AliasIdxRaw);
5186   // Is the allocation's memory state untouched?
5187   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
5188     // Bail out if there have been raw-memory effects since the allocation.
5189     // (Example:  There might have been a call or safepoint.)
5190     return NULL;
5191   }
5192   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
5193   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
5194     return NULL;
5195   }
5196 
5197   // There must be no unexpected observers of this allocation.
5198   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
5199     Node* obs = ptr->fast_out(i);
5200     if (obs != this->map()) {
5201       return NULL;
5202     }
5203   }
5204 
5205   // This arraycopy must unconditionally follow the allocation of the ptr.
5206   Node* alloc_ctl = ptr->in(0);
5207   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
5208 
5209   Node* ctl = control();
5210   while (ctl != alloc_ctl) {
5211     // There may be guards which feed into the slow_region.
5212     // Any other control flow means that we might not get a chance
5213     // to finish initializing the allocated object.
5214     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
5215       IfNode* iff = ctl->in(0)->as_If();
5216       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
5217       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
5218       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
5219         ctl = iff->in(0);       // This test feeds the known slow_region.
5220         continue;
5221       }
5222       // One more try:  Various low-level checks bottom out in
5223       // uncommon traps.  If the debug-info of the trap omits
5224       // any reference to the allocation, as we've already
5225       // observed, then there can be no objection to the trap.
5226       bool found_trap = false;
5227       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
5228         Node* obs = not_ctl->fast_out(j);
5229         if (obs->in(0) == not_ctl && obs->is_Call() &&
5230             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
5231           found_trap = true; break;
5232         }
5233       }
5234       if (found_trap) {
5235         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
5236         continue;
5237       }
5238     }
5239     return NULL;
5240   }
5241 
5242   // If we get this far, we have an allocation which immediately
5243   // precedes the arraycopy, and we can take over zeroing the new object.
5244   // The arraycopy will finish the initialization, and provide
5245   // a new control state to which we will anchor the destination pointer.
5246 
5247   return alloc;
5248 }
5249 
5250 //-------------inline_encodeISOArray-----------------------------------
5251 // encode char[] to byte[] in ISO_8859_1
5252 bool LibraryCallKit::inline_encodeISOArray() {
5253   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
5254   // no receiver since it is static method
5255   Node *src         = argument(0);
5256   Node *src_offset  = argument(1);
5257   Node *dst         = argument(2);
5258   Node *dst_offset  = argument(3);
5259   Node *length      = argument(4);
5260 
5261   const Type* src_type = src->Value(&_gvn);
5262   const Type* dst_type = dst->Value(&_gvn);
5263   const TypeAryPtr* top_src = src_type->isa_aryptr();
5264   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
5265   if (top_src  == NULL || top_src->klass()  == NULL ||
5266       top_dest == NULL || top_dest->klass() == NULL) {
5267     // failed array check
5268     return false;
5269   }
5270 
5271   // Figure out the size and type of the elements we will be copying.
5272   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5273   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5274   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
5275     return false;
5276   }
5277 
5278   Node* src_start = array_element_address(src, src_offset, T_CHAR);
5279   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
5280   // 'src_start' points to src array + scaled offset
5281   // 'dst_start' points to dst array + scaled offset
5282 
5283   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
5284   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
5285   enc = _gvn.transform(enc);
5286   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
5287   set_memory(res_mem, mtype);
5288   set_result(enc);
5289   return true;
5290 }
5291 
5292 //-------------inline_multiplyToLen-----------------------------------
5293 bool LibraryCallKit::inline_multiplyToLen() {
5294   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
5295 
5296   address stubAddr = StubRoutines::multiplyToLen();
5297   if (stubAddr == NULL) {
5298     return false; // Intrinsic's stub is not implemented on this platform
5299   }
5300   const char* stubName = "multiplyToLen";
5301 
5302   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
5303 
5304   // no receiver because it is a static method
5305   Node* x    = argument(0);
5306   Node* xlen = argument(1);
5307   Node* y    = argument(2);
5308   Node* ylen = argument(3);
5309   Node* z    = argument(4);
5310 
5311   const Type* x_type = x->Value(&_gvn);
5312   const Type* y_type = y->Value(&_gvn);
5313   const TypeAryPtr* top_x = x_type->isa_aryptr();
5314   const TypeAryPtr* top_y = y_type->isa_aryptr();
5315   if (top_x  == NULL || top_x->klass()  == NULL ||
5316       top_y == NULL || top_y->klass() == NULL) {
5317     // failed array check
5318     return false;
5319   }
5320 
5321   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5322   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5323   if (x_elem != T_INT || y_elem != T_INT) {
5324     return false;
5325   }
5326 
5327   // Set the original stack and the reexecute bit for the interpreter to reexecute
5328   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
5329   // on the return from z array allocation in runtime.
5330   { PreserveReexecuteState preexecs(this);
5331     jvms()->set_should_reexecute(true);
5332 
5333     Node* x_start = array_element_address(x, intcon(0), x_elem);
5334     Node* y_start = array_element_address(y, intcon(0), y_elem);
5335     // 'x_start' points to x array + scaled xlen
5336     // 'y_start' points to y array + scaled ylen
5337 
5338     // Allocate the result array
5339     Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
5340     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
5341     Node* klass_node = makecon(TypeKlassPtr::make(klass));
5342 
5343     IdealKit ideal(this);
5344 
5345 #define __ ideal.
5346      Node* one = __ ConI(1);
5347      Node* zero = __ ConI(0);
5348      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
5349      __ set(need_alloc, zero);
5350      __ set(z_alloc, z);
5351      __ if_then(z, BoolTest::eq, null()); {
5352        __ increment (need_alloc, one);
5353      } __ else_(); {
5354        // Update graphKit memory and control from IdealKit.
5355        sync_kit(ideal);
5356        Node* zlen_arg = load_array_length(z);
5357        // Update IdealKit memory and control from graphKit.
5358        __ sync_kit(this);
5359        __ if_then(zlen_arg, BoolTest::lt, zlen); {
5360          __ increment (need_alloc, one);
5361        } __ end_if();
5362      } __ end_if();
5363 
5364      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
5365        // Update graphKit memory and control from IdealKit.
5366        sync_kit(ideal);
5367        Node * narr = new_array(klass_node, zlen, 1);
5368        // Update IdealKit memory and control from graphKit.
5369        __ sync_kit(this);
5370        __ set(z_alloc, narr);
5371      } __ end_if();
5372 
5373      sync_kit(ideal);
5374      z = __ value(z_alloc);
5375      // Can't use TypeAryPtr::INTS which uses Bottom offset.
5376      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
5377      // Final sync IdealKit and GraphKit.
5378      final_sync(ideal);
5379 #undef __
5380 
5381     Node* z_start = array_element_address(z, intcon(0), T_INT);
5382 
5383     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5384                                    OptoRuntime::multiplyToLen_Type(),
5385                                    stubAddr, stubName, TypePtr::BOTTOM,
5386                                    x_start, xlen, y_start, ylen, z_start, zlen);
5387   } // original reexecute is set back here
5388 
5389   C->set_has_split_ifs(true); // Has chance for split-if optimization
5390   set_result(z);
5391   return true;
5392 }
5393 
5394 //-------------inline_squareToLen------------------------------------
5395 bool LibraryCallKit::inline_squareToLen() {
5396   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
5397 
5398   address stubAddr = StubRoutines::squareToLen();
5399   if (stubAddr == NULL) {
5400     return false; // Intrinsic's stub is not implemented on this platform
5401   }
5402   const char* stubName = "squareToLen";
5403 
5404   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
5405 
5406   Node* x    = argument(0);
5407   Node* len  = argument(1);
5408   Node* z    = argument(2);
5409   Node* zlen = argument(3);
5410 
5411   const Type* x_type = x->Value(&_gvn);
5412   const Type* z_type = z->Value(&_gvn);
5413   const TypeAryPtr* top_x = x_type->isa_aryptr();
5414   const TypeAryPtr* top_z = z_type->isa_aryptr();
5415   if (top_x  == NULL || top_x->klass()  == NULL ||
5416       top_z  == NULL || top_z->klass()  == NULL) {
5417     // failed array check
5418     return false;
5419   }
5420 
5421   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5422   BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5423   if (x_elem != T_INT || z_elem != T_INT) {
5424     return false;
5425   }
5426 
5427 
5428   Node* x_start = array_element_address(x, intcon(0), x_elem);
5429   Node* z_start = array_element_address(z, intcon(0), z_elem);
5430 
5431   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5432                                   OptoRuntime::squareToLen_Type(),
5433                                   stubAddr, stubName, TypePtr::BOTTOM,
5434                                   x_start, len, z_start, zlen);
5435 
5436   set_result(z);
5437   return true;
5438 }
5439 
5440 //-------------inline_mulAdd------------------------------------------
5441 bool LibraryCallKit::inline_mulAdd() {
5442   assert(UseMulAddIntrinsic, "not implemented on this platform");
5443 
5444   address stubAddr = StubRoutines::mulAdd();
5445   if (stubAddr == NULL) {
5446     return false; // Intrinsic's stub is not implemented on this platform
5447   }
5448   const char* stubName = "mulAdd";
5449 
5450   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
5451 
5452   Node* out      = argument(0);
5453   Node* in       = argument(1);
5454   Node* offset   = argument(2);
5455   Node* len      = argument(3);
5456   Node* k        = argument(4);
5457 
5458   const Type* out_type = out->Value(&_gvn);
5459   const Type* in_type = in->Value(&_gvn);
5460   const TypeAryPtr* top_out = out_type->isa_aryptr();
5461   const TypeAryPtr* top_in = in_type->isa_aryptr();
5462   if (top_out  == NULL || top_out->klass()  == NULL ||
5463       top_in == NULL || top_in->klass() == NULL) {
5464     // failed array check
5465     return false;
5466   }
5467 
5468   BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5469   BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5470   if (out_elem != T_INT || in_elem != T_INT) {
5471     return false;
5472   }
5473 
5474   Node* outlen = load_array_length(out);
5475   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
5476   Node* out_start = array_element_address(out, intcon(0), out_elem);
5477   Node* in_start = array_element_address(in, intcon(0), in_elem);
5478 
5479   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
5480                                   OptoRuntime::mulAdd_Type(),
5481                                   stubAddr, stubName, TypePtr::BOTTOM,
5482                                   out_start,in_start, new_offset, len, k);
5483   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5484   set_result(result);
5485   return true;
5486 }
5487 
5488 //-------------inline_montgomeryMultiply-----------------------------------
5489 bool LibraryCallKit::inline_montgomeryMultiply() {
5490   address stubAddr = StubRoutines::montgomeryMultiply();
5491   if (stubAddr == NULL) {
5492     return false; // Intrinsic's stub is not implemented on this platform
5493   }
5494 
5495   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
5496   const char* stubName = "montgomery_square";
5497 
5498   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
5499 
5500   Node* a    = argument(0);
5501   Node* b    = argument(1);
5502   Node* n    = argument(2);
5503   Node* len  = argument(3);
5504   Node* inv  = argument(4);
5505   Node* m    = argument(6);
5506 
5507   const Type* a_type = a->Value(&_gvn);
5508   const TypeAryPtr* top_a = a_type->isa_aryptr();
5509   const Type* b_type = b->Value(&_gvn);
5510   const TypeAryPtr* top_b = b_type->isa_aryptr();
5511   const Type* n_type = a->Value(&_gvn);
5512   const TypeAryPtr* top_n = n_type->isa_aryptr();
5513   const Type* m_type = a->Value(&_gvn);
5514   const TypeAryPtr* top_m = m_type->isa_aryptr();
5515   if (top_a  == NULL || top_a->klass()  == NULL ||
5516       top_b == NULL || top_b->klass()  == NULL ||
5517       top_n == NULL || top_n->klass()  == NULL ||
5518       top_m == NULL || top_m->klass()  == NULL) {
5519     // failed array check
5520     return false;
5521   }
5522 
5523   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5524   BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5525   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5526   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5527   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5528     return false;
5529   }
5530 
5531   // Make the call
5532   {
5533     Node* a_start = array_element_address(a, intcon(0), a_elem);
5534     Node* b_start = array_element_address(b, intcon(0), b_elem);
5535     Node* n_start = array_element_address(n, intcon(0), n_elem);
5536     Node* m_start = array_element_address(m, intcon(0), m_elem);
5537 
5538     Node* call = make_runtime_call(RC_LEAF,
5539                                    OptoRuntime::montgomeryMultiply_Type(),
5540                                    stubAddr, stubName, TypePtr::BOTTOM,
5541                                    a_start, b_start, n_start, len, inv, top(),
5542                                    m_start);
5543     set_result(m);
5544   }
5545 
5546   return true;
5547 }
5548 
5549 bool LibraryCallKit::inline_montgomerySquare() {
5550   address stubAddr = StubRoutines::montgomerySquare();
5551   if (stubAddr == NULL) {
5552     return false; // Intrinsic's stub is not implemented on this platform
5553   }
5554 
5555   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5556   const char* stubName = "montgomery_square";
5557 
5558   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5559 
5560   Node* a    = argument(0);
5561   Node* n    = argument(1);
5562   Node* len  = argument(2);
5563   Node* inv  = argument(3);
5564   Node* m    = argument(5);
5565 
5566   const Type* a_type = a->Value(&_gvn);
5567   const TypeAryPtr* top_a = a_type->isa_aryptr();
5568   const Type* n_type = a->Value(&_gvn);
5569   const TypeAryPtr* top_n = n_type->isa_aryptr();
5570   const Type* m_type = a->Value(&_gvn);
5571   const TypeAryPtr* top_m = m_type->isa_aryptr();
5572   if (top_a  == NULL || top_a->klass()  == NULL ||
5573       top_n == NULL || top_n->klass()  == NULL ||
5574       top_m == NULL || top_m->klass()  == NULL) {
5575     // failed array check
5576     return false;
5577   }
5578 
5579   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5580   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5581   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5582   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5583     return false;
5584   }
5585 
5586   // Make the call
5587   {
5588     Node* a_start = array_element_address(a, intcon(0), a_elem);
5589     Node* n_start = array_element_address(n, intcon(0), n_elem);
5590     Node* m_start = array_element_address(m, intcon(0), m_elem);
5591 
5592     Node* call = make_runtime_call(RC_LEAF,
5593                                    OptoRuntime::montgomerySquare_Type(),
5594                                    stubAddr, stubName, TypePtr::BOTTOM,
5595                                    a_start, n_start, len, inv, top(),
5596                                    m_start);
5597     set_result(m);
5598   }
5599 
5600   return true;
5601 }
5602 
5603 //-------------inline_vectorizedMismatch------------------------------
5604 bool LibraryCallKit::inline_vectorizedMismatch() {
5605   assert(UseVectorizedMismatchIntrinsic, "not implementated on this platform");
5606 
5607   address stubAddr = StubRoutines::vectorizedMismatch();
5608   if (stubAddr == NULL) {
5609     return false; // Intrinsic's stub is not implemented on this platform
5610   }
5611   const char* stubName = "vectorizedMismatch";
5612   int size_l = callee()->signature()->size();
5613   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
5614 
5615   Node* obja = argument(0);
5616   Node* aoffset = argument(1);
5617   Node* objb = argument(3);
5618   Node* boffset = argument(4);
5619   Node* length = argument(6);
5620   Node* scale = argument(7);
5621 
5622   const Type* a_type = obja->Value(&_gvn);
5623   const Type* b_type = objb->Value(&_gvn);
5624   const TypeAryPtr* top_a = a_type->isa_aryptr();
5625   const TypeAryPtr* top_b = b_type->isa_aryptr();
5626   if (top_a == NULL || top_a->klass() == NULL ||
5627     top_b == NULL || top_b->klass() == NULL) {
5628     // failed array check
5629     return false;
5630   }
5631 
5632   Node* call;
5633   jvms()->set_should_reexecute(true);
5634 
5635   Node* obja_adr = make_unsafe_address(obja, aoffset);
5636   Node* objb_adr = make_unsafe_address(objb, boffset);
5637 
5638   call = make_runtime_call(RC_LEAF,
5639     OptoRuntime::vectorizedMismatch_Type(),
5640     stubAddr, stubName, TypePtr::BOTTOM,
5641     obja_adr, objb_adr, length, scale);
5642 
5643   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5644   set_result(result);
5645   return true;
5646 }
5647 
5648 /**
5649  * Calculate CRC32 for byte.
5650  * int java.util.zip.CRC32.update(int crc, int b)
5651  */
5652 bool LibraryCallKit::inline_updateCRC32() {
5653   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5654   assert(callee()->signature()->size() == 2, "update has 2 parameters");
5655   // no receiver since it is static method
5656   Node* crc  = argument(0); // type: int
5657   Node* b    = argument(1); // type: int
5658 
5659   /*
5660    *    int c = ~ crc;
5661    *    b = timesXtoThe32[(b ^ c) & 0xFF];
5662    *    b = b ^ (c >>> 8);
5663    *    crc = ~b;
5664    */
5665 
5666   Node* M1 = intcon(-1);
5667   crc = _gvn.transform(new XorINode(crc, M1));
5668   Node* result = _gvn.transform(new XorINode(crc, b));
5669   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5670 
5671   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5672   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5673   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5674   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5675 
5676   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5677   result = _gvn.transform(new XorINode(crc, result));
5678   result = _gvn.transform(new XorINode(result, M1));
5679   set_result(result);
5680   return true;
5681 }
5682 
5683 /**
5684  * Calculate CRC32 for byte[] array.
5685  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5686  */
5687 bool LibraryCallKit::inline_updateBytesCRC32() {
5688   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5689   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5690   // no receiver since it is static method
5691   Node* crc     = argument(0); // type: int
5692   Node* src     = argument(1); // type: oop
5693   Node* offset  = argument(2); // type: int
5694   Node* length  = argument(3); // type: int
5695 
5696   const Type* src_type = src->Value(&_gvn);
5697   const TypeAryPtr* top_src = src_type->isa_aryptr();
5698   if (top_src  == NULL || top_src->klass()  == NULL) {
5699     // failed array check
5700     return false;
5701   }
5702 
5703   // Figure out the size and type of the elements we will be copying.
5704   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5705   if (src_elem != T_BYTE) {
5706     return false;
5707   }
5708 
5709   // 'src_start' points to src array + scaled offset
5710   Node* src_start = array_element_address(src, offset, src_elem);
5711 
5712   // We assume that range check is done by caller.
5713   // TODO: generate range check (offset+length < src.length) in debug VM.
5714 
5715   // Call the stub.
5716   address stubAddr = StubRoutines::updateBytesCRC32();
5717   const char *stubName = "updateBytesCRC32";
5718 
5719   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5720                                  stubAddr, stubName, TypePtr::BOTTOM,
5721                                  crc, src_start, length);
5722   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5723   set_result(result);
5724   return true;
5725 }
5726 
5727 /**
5728  * Calculate CRC32 for ByteBuffer.
5729  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5730  */
5731 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5732   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5733   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5734   // no receiver since it is static method
5735   Node* crc     = argument(0); // type: int
5736   Node* src     = argument(1); // type: long
5737   Node* offset  = argument(3); // type: int
5738   Node* length  = argument(4); // type: int
5739 
5740   src = ConvL2X(src);  // adjust Java long to machine word
5741   Node* base = _gvn.transform(new CastX2PNode(src));
5742   offset = ConvI2X(offset);
5743 
5744   // 'src_start' points to src array + scaled offset
5745   Node* src_start = basic_plus_adr(top(), base, offset);
5746 
5747   // Call the stub.
5748   address stubAddr = StubRoutines::updateBytesCRC32();
5749   const char *stubName = "updateBytesCRC32";
5750 
5751   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5752                                  stubAddr, stubName, TypePtr::BOTTOM,
5753                                  crc, src_start, length);
5754   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5755   set_result(result);
5756   return true;
5757 }
5758 
5759 //------------------------------get_table_from_crc32c_class-----------------------
5760 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5761   Node* table = load_field_from_object(NULL, "byteTable", "[I", /*is_exact*/ false, /*is_static*/ true, crc32c_class);
5762   assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5763 
5764   return table;
5765 }
5766 
5767 //------------------------------inline_updateBytesCRC32C-----------------------
5768 //
5769 // Calculate CRC32C for byte[] array.
5770 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5771 //
5772 bool LibraryCallKit::inline_updateBytesCRC32C() {
5773   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5774   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5775   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5776   // no receiver since it is a static method
5777   Node* crc     = argument(0); // type: int
5778   Node* src     = argument(1); // type: oop
5779   Node* offset  = argument(2); // type: int
5780   Node* end     = argument(3); // type: int
5781 
5782   Node* length = _gvn.transform(new SubINode(end, offset));
5783 
5784   const Type* src_type = src->Value(&_gvn);
5785   const TypeAryPtr* top_src = src_type->isa_aryptr();
5786   if (top_src  == NULL || top_src->klass()  == NULL) {
5787     // failed array check
5788     return false;
5789   }
5790 
5791   // Figure out the size and type of the elements we will be copying.
5792   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5793   if (src_elem != T_BYTE) {
5794     return false;
5795   }
5796 
5797   // 'src_start' points to src array + scaled offset
5798   Node* src_start = array_element_address(src, offset, src_elem);
5799 
5800   // static final int[] byteTable in class CRC32C
5801   Node* table = get_table_from_crc32c_class(callee()->holder());
5802   Node* table_start = array_element_address(table, intcon(0), T_INT);
5803 
5804   // We assume that range check is done by caller.
5805   // TODO: generate range check (offset+length < src.length) in debug VM.
5806 
5807   // Call the stub.
5808   address stubAddr = StubRoutines::updateBytesCRC32C();
5809   const char *stubName = "updateBytesCRC32C";
5810 
5811   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5812                                  stubAddr, stubName, TypePtr::BOTTOM,
5813                                  crc, src_start, length, table_start);
5814   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5815   set_result(result);
5816   return true;
5817 }
5818 
5819 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
5820 //
5821 // Calculate CRC32C for DirectByteBuffer.
5822 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
5823 //
5824 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
5825   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5826   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
5827   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5828   // no receiver since it is a static method
5829   Node* crc     = argument(0); // type: int
5830   Node* src     = argument(1); // type: long
5831   Node* offset  = argument(3); // type: int
5832   Node* end     = argument(4); // type: int
5833 
5834   Node* length = _gvn.transform(new SubINode(end, offset));
5835 
5836   src = ConvL2X(src);  // adjust Java long to machine word
5837   Node* base = _gvn.transform(new CastX2PNode(src));
5838   offset = ConvI2X(offset);
5839 
5840   // 'src_start' points to src array + scaled offset
5841   Node* src_start = basic_plus_adr(top(), base, offset);
5842 
5843   // static final int[] byteTable in class CRC32C
5844   Node* table = get_table_from_crc32c_class(callee()->holder());
5845   Node* table_start = array_element_address(table, intcon(0), T_INT);
5846 
5847   // Call the stub.
5848   address stubAddr = StubRoutines::updateBytesCRC32C();
5849   const char *stubName = "updateBytesCRC32C";
5850 
5851   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5852                                  stubAddr, stubName, TypePtr::BOTTOM,
5853                                  crc, src_start, length, table_start);
5854   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5855   set_result(result);
5856   return true;
5857 }
5858 
5859 //------------------------------inline_updateBytesAdler32----------------------
5860 //
5861 // Calculate Adler32 checksum for byte[] array.
5862 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
5863 //
5864 bool LibraryCallKit::inline_updateBytesAdler32() {
5865   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5866   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5867   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5868   // no receiver since it is static method
5869   Node* crc     = argument(0); // type: int
5870   Node* src     = argument(1); // type: oop
5871   Node* offset  = argument(2); // type: int
5872   Node* length  = argument(3); // type: int
5873 
5874   const Type* src_type = src->Value(&_gvn);
5875   const TypeAryPtr* top_src = src_type->isa_aryptr();
5876   if (top_src  == NULL || top_src->klass()  == NULL) {
5877     // failed array check
5878     return false;
5879   }
5880 
5881   // Figure out the size and type of the elements we will be copying.
5882   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5883   if (src_elem != T_BYTE) {
5884     return false;
5885   }
5886 
5887   // 'src_start' points to src array + scaled offset
5888   Node* src_start = array_element_address(src, offset, src_elem);
5889 
5890   // We assume that range check is done by caller.
5891   // TODO: generate range check (offset+length < src.length) in debug VM.
5892 
5893   // Call the stub.
5894   address stubAddr = StubRoutines::updateBytesAdler32();
5895   const char *stubName = "updateBytesAdler32";
5896 
5897   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5898                                  stubAddr, stubName, TypePtr::BOTTOM,
5899                                  crc, src_start, length);
5900   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5901   set_result(result);
5902   return true;
5903 }
5904 
5905 //------------------------------inline_updateByteBufferAdler32---------------
5906 //
5907 // Calculate Adler32 checksum for DirectByteBuffer.
5908 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
5909 //
5910 bool LibraryCallKit::inline_updateByteBufferAdler32() {
5911   assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5912   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5913   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5914   // no receiver since it is static method
5915   Node* crc     = argument(0); // type: int
5916   Node* src     = argument(1); // type: long
5917   Node* offset  = argument(3); // type: int
5918   Node* length  = argument(4); // type: int
5919 
5920   src = ConvL2X(src);  // adjust Java long to machine word
5921   Node* base = _gvn.transform(new CastX2PNode(src));
5922   offset = ConvI2X(offset);
5923 
5924   // 'src_start' points to src array + scaled offset
5925   Node* src_start = basic_plus_adr(top(), base, offset);
5926 
5927   // Call the stub.
5928   address stubAddr = StubRoutines::updateBytesAdler32();
5929   const char *stubName = "updateBytesAdler32";
5930 
5931   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5932                                  stubAddr, stubName, TypePtr::BOTTOM,
5933                                  crc, src_start, length);
5934 
5935   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5936   set_result(result);
5937   return true;
5938 }
5939 
5940 //----------------------------inline_reference_get----------------------------
5941 // public T java.lang.ref.Reference.get();
5942 bool LibraryCallKit::inline_reference_get() {
5943   const int referent_offset = java_lang_ref_Reference::referent_offset;
5944   guarantee(referent_offset > 0, "should have already been set");
5945 
5946   // Get the argument:
5947   Node* reference_obj = null_check_receiver();
5948   if (stopped()) return true;
5949 
5950   Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
5951 
5952   ciInstanceKlass* klass = env()->Object_klass();
5953   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
5954 
5955   Node* no_ctrl = NULL;
5956   Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
5957 
5958   // Use the pre-barrier to record the value in the referent field
5959   pre_barrier(false /* do_load */,
5960               control(),
5961               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
5962               result /* pre_val */,
5963               T_OBJECT);
5964 
5965   // Add memory barrier to prevent commoning reads from this field
5966   // across safepoint since GC can change its value.
5967   insert_mem_bar(Op_MemBarCPUOrder);
5968 
5969   set_result(result);
5970   return true;
5971 }
5972 
5973 
5974 Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5975                                               bool is_exact=true, bool is_static=false,
5976                                               ciInstanceKlass * fromKls=NULL) {
5977   if (fromKls == NULL) {
5978     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5979     assert(tinst != NULL, "obj is null");
5980     assert(tinst->klass()->is_loaded(), "obj is not loaded");
5981     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5982     fromKls = tinst->klass()->as_instance_klass();
5983   } else {
5984     assert(is_static, "only for static field access");
5985   }
5986   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
5987                                               ciSymbol::make(fieldTypeString),
5988                                               is_static);
5989 
5990   assert (field != NULL, "undefined field");
5991   if (field == NULL) return (Node *) NULL;
5992 
5993   if (is_static) {
5994     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
5995     fromObj = makecon(tip);
5996   }
5997 
5998   // Next code  copied from Parse::do_get_xxx():
5999 
6000   // Compute address and memory type.
6001   int offset  = field->offset_in_bytes();
6002   bool is_vol = field->is_volatile();
6003   ciType* field_klass = field->type();
6004   assert(field_klass->is_loaded(), "should be loaded");
6005   const TypePtr* adr_type = C->alias_type(field)->adr_type();
6006   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6007   BasicType bt = field->layout_type();
6008 
6009   // Build the resultant type of the load
6010   const Type *type;
6011   if (bt == T_OBJECT) {
6012     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
6013   } else {
6014     type = Type::get_const_basic_type(bt);
6015   }
6016 
6017   if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
6018     insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
6019   }
6020   // Build the load.
6021   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
6022   Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);
6023   // If reference is volatile, prevent following memory ops from
6024   // floating up past the volatile read.  Also prevents commoning
6025   // another volatile read.
6026   if (is_vol) {
6027     // Memory barrier includes bogus read of value to force load BEFORE membar
6028     insert_mem_bar(Op_MemBarAcquire, loadedField);
6029   }
6030   return loadedField;
6031 }
6032 
6033 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
6034                                                  bool is_exact = true, bool is_static = false,
6035                                                  ciInstanceKlass * fromKls = NULL) {
6036   if (fromKls == NULL) {
6037     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
6038     assert(tinst != NULL, "obj is null");
6039     assert(tinst->klass()->is_loaded(), "obj is not loaded");
6040     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
6041     fromKls = tinst->klass()->as_instance_klass();
6042   }
6043   else {
6044     assert(is_static, "only for static field access");
6045   }
6046   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
6047     ciSymbol::make(fieldTypeString),
6048     is_static);
6049 
6050   assert(field != NULL, "undefined field");
6051   assert(!field->is_volatile(), "not defined for volatile fields");
6052 
6053   if (is_static) {
6054     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
6055     fromObj = makecon(tip);
6056   }
6057 
6058   // Next code  copied from Parse::do_get_xxx():
6059 
6060   // Compute address and memory type.
6061   int offset = field->offset_in_bytes();
6062   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
6063 
6064   return adr;
6065 }
6066 
6067 //------------------------------inline_aescrypt_Block-----------------------
6068 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
6069   address stubAddr = NULL;
6070   const char *stubName;
6071   assert(UseAES, "need AES instruction support");
6072 
6073   switch(id) {
6074   case vmIntrinsics::_aescrypt_encryptBlock:
6075     stubAddr = StubRoutines::aescrypt_encryptBlock();
6076     stubName = "aescrypt_encryptBlock";
6077     break;
6078   case vmIntrinsics::_aescrypt_decryptBlock:
6079     stubAddr = StubRoutines::aescrypt_decryptBlock();
6080     stubName = "aescrypt_decryptBlock";
6081     break;
6082   }
6083   if (stubAddr == NULL) return false;
6084 
6085   Node* aescrypt_object = argument(0);
6086   Node* src             = argument(1);
6087   Node* src_offset      = argument(2);
6088   Node* dest            = argument(3);
6089   Node* dest_offset     = argument(4);
6090 
6091   // (1) src and dest are arrays.
6092   const Type* src_type = src->Value(&_gvn);
6093   const Type* dest_type = dest->Value(&_gvn);
6094   const TypeAryPtr* top_src = src_type->isa_aryptr();
6095   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6096   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6097 
6098   // for the quick and dirty code we will skip all the checks.
6099   // we are just trying to get the call to be generated.
6100   Node* src_start  = src;
6101   Node* dest_start = dest;
6102   if (src_offset != NULL || dest_offset != NULL) {
6103     assert(src_offset != NULL && dest_offset != NULL, "");
6104     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6105     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6106   }
6107 
6108   // now need to get the start of its expanded key array
6109   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6110   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6111   if (k_start == NULL) return false;
6112 
6113   if (Matcher::pass_original_key_for_aes()) {
6114     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6115     // compatibility issues between Java key expansion and SPARC crypto instructions
6116     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6117     if (original_k_start == NULL) return false;
6118 
6119     // Call the stub.
6120     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6121                       stubAddr, stubName, TypePtr::BOTTOM,
6122                       src_start, dest_start, k_start, original_k_start);
6123   } else {
6124     // Call the stub.
6125     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
6126                       stubAddr, stubName, TypePtr::BOTTOM,
6127                       src_start, dest_start, k_start);
6128   }
6129 
6130   return true;
6131 }
6132 
6133 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
6134 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
6135   address stubAddr = NULL;
6136   const char *stubName = NULL;
6137 
6138   assert(UseAES, "need AES instruction support");
6139 
6140   switch(id) {
6141   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
6142     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
6143     stubName = "cipherBlockChaining_encryptAESCrypt";
6144     break;
6145   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
6146     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
6147     stubName = "cipherBlockChaining_decryptAESCrypt";
6148     break;
6149   }
6150   if (stubAddr == NULL) return false;
6151 
6152   Node* cipherBlockChaining_object = argument(0);
6153   Node* src                        = argument(1);
6154   Node* src_offset                 = argument(2);
6155   Node* len                        = argument(3);
6156   Node* dest                       = argument(4);
6157   Node* dest_offset                = argument(5);
6158 
6159   // (1) src and dest are arrays.
6160   const Type* src_type = src->Value(&_gvn);
6161   const Type* dest_type = dest->Value(&_gvn);
6162   const TypeAryPtr* top_src = src_type->isa_aryptr();
6163   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6164   assert (top_src  != NULL && top_src->klass()  != NULL
6165           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6166 
6167   // checks are the responsibility of the caller
6168   Node* src_start  = src;
6169   Node* dest_start = dest;
6170   if (src_offset != NULL || dest_offset != NULL) {
6171     assert(src_offset != NULL && dest_offset != NULL, "");
6172     src_start  = array_element_address(src,  src_offset,  T_BYTE);
6173     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6174   }
6175 
6176   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6177   // (because of the predicated logic executed earlier).
6178   // so we cast it here safely.
6179   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6180 
6181   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6182   if (embeddedCipherObj == NULL) return false;
6183 
6184   // cast it to what we know it will be at runtime
6185   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
6186   assert(tinst != NULL, "CBC obj is null");
6187   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
6188   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6189   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6190 
6191   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6192   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6193   const TypeOopPtr* xtype = aklass->as_instance_type();
6194   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6195   aescrypt_object = _gvn.transform(aescrypt_object);
6196 
6197   // we need to get the start of the aescrypt_object's expanded key array
6198   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6199   if (k_start == NULL) return false;
6200 
6201   // similarly, get the start address of the r vector
6202   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
6203   if (objRvec == NULL) return false;
6204   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
6205 
6206   Node* cbcCrypt;
6207   if (Matcher::pass_original_key_for_aes()) {
6208     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
6209     // compatibility issues between Java key expansion and SPARC crypto instructions
6210     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
6211     if (original_k_start == NULL) return false;
6212 
6213     // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
6214     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6215                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6216                                  stubAddr, stubName, TypePtr::BOTTOM,
6217                                  src_start, dest_start, k_start, r_start, len, original_k_start);
6218   } else {
6219     // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6220     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6221                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
6222                                  stubAddr, stubName, TypePtr::BOTTOM,
6223                                  src_start, dest_start, k_start, r_start, len);
6224   }
6225 
6226   // return cipher length (int)
6227   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
6228   set_result(retvalue);
6229   return true;
6230 }
6231 
6232 //------------------------------inline_counterMode_AESCrypt-----------------------
6233 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
6234   assert(UseAES, "need AES instruction support");
6235   if (!UseAESCTRIntrinsics) return false;
6236 
6237   address stubAddr = NULL;
6238   const char *stubName = NULL;
6239   if (id == vmIntrinsics::_counterMode_AESCrypt) {
6240     stubAddr = StubRoutines::counterMode_AESCrypt();
6241     stubName = "counterMode_AESCrypt";
6242   }
6243   if (stubAddr == NULL) return false;
6244 
6245   Node* counterMode_object = argument(0);
6246   Node* src = argument(1);
6247   Node* src_offset = argument(2);
6248   Node* len = argument(3);
6249   Node* dest = argument(4);
6250   Node* dest_offset = argument(5);
6251 
6252   // (1) src and dest are arrays.
6253   const Type* src_type = src->Value(&_gvn);
6254   const Type* dest_type = dest->Value(&_gvn);
6255   const TypeAryPtr* top_src = src_type->isa_aryptr();
6256   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6257   assert(top_src != NULL && top_src->klass() != NULL &&
6258          top_dest != NULL && top_dest->klass() != NULL, "args are strange");
6259 
6260   // checks are the responsibility of the caller
6261   Node* src_start = src;
6262   Node* dest_start = dest;
6263   if (src_offset != NULL || dest_offset != NULL) {
6264     assert(src_offset != NULL && dest_offset != NULL, "");
6265     src_start = array_element_address(src, src_offset, T_BYTE);
6266     dest_start = array_element_address(dest, dest_offset, T_BYTE);
6267   }
6268 
6269   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
6270   // (because of the predicated logic executed earlier).
6271   // so we cast it here safely.
6272   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
6273   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6274   if (embeddedCipherObj == NULL) return false;
6275   // cast it to what we know it will be at runtime
6276   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
6277   assert(tinst != NULL, "CTR obj is null");
6278   assert(tinst->klass()->is_loaded(), "CTR obj is not loaded");
6279   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6280   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
6281   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6282   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
6283   const TypeOopPtr* xtype = aklass->as_instance_type();
6284   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
6285   aescrypt_object = _gvn.transform(aescrypt_object);
6286   // we need to get the start of the aescrypt_object's expanded key array
6287   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
6288   if (k_start == NULL) return false;
6289   // similarly, get the start address of the r vector
6290   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B", /*is_exact*/ false);
6291   if (obj_counter == NULL) return false;
6292   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
6293 
6294   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B", /*is_exact*/ false);
6295   if (saved_encCounter == NULL) return false;
6296   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
6297   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
6298 
6299   Node* ctrCrypt;
6300   if (Matcher::pass_original_key_for_aes()) {
6301     // no SPARC version for AES/CTR intrinsics now.
6302     return false;
6303   }
6304   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
6305   ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
6306                                OptoRuntime::counterMode_aescrypt_Type(),
6307                                stubAddr, stubName, TypePtr::BOTTOM,
6308                                src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
6309 
6310   // return cipher length (int)
6311   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
6312   set_result(retvalue);
6313   return true;
6314 }
6315 
6316 //------------------------------get_key_start_from_aescrypt_object-----------------------
6317 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
6318   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
6319   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6320   if (objAESCryptKey == NULL) return (Node *) NULL;
6321 
6322   // now have the array, need to get the start address of the K array
6323   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
6324   return k_start;
6325 }
6326 
6327 //------------------------------get_original_key_start_from_aescrypt_object-----------------------
6328 Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
6329   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
6330   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
6331   if (objAESCryptKey == NULL) return (Node *) NULL;
6332 
6333   // now have the array, need to get the start address of the lastKey array
6334   Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
6335   return original_k_start;
6336 }
6337 
6338 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
6339 // Return node representing slow path of predicate check.
6340 // the pseudo code we want to emulate with this predicate is:
6341 // for encryption:
6342 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6343 // for decryption:
6344 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6345 //    note cipher==plain is more conservative than the original java code but that's OK
6346 //
6347 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
6348   // The receiver was checked for NULL already.
6349   Node* objCBC = argument(0);
6350 
6351   // Load embeddedCipher field of CipherBlockChaining object.
6352   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6353 
6354   // get AESCrypt klass for instanceOf check
6355   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6356   // will have same classloader as CipherBlockChaining object
6357   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
6358   assert(tinst != NULL, "CBCobj is null");
6359   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
6360 
6361   // we want to do an instanceof comparison against the AESCrypt class
6362   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6363   if (!klass_AESCrypt->is_loaded()) {
6364     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6365     Node* ctrl = control();
6366     set_control(top()); // no regular fast path
6367     return ctrl;
6368   }
6369   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6370 
6371   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6372   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
6373   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6374 
6375   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6376 
6377   // for encryption, we are done
6378   if (!decrypting)
6379     return instof_false;  // even if it is NULL
6380 
6381   // for decryption, we need to add a further check to avoid
6382   // taking the intrinsic path when cipher and plain are the same
6383   // see the original java code for why.
6384   RegionNode* region = new RegionNode(3);
6385   region->init_req(1, instof_false);
6386   Node* src = argument(1);
6387   Node* dest = argument(4);
6388   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6389   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6390   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6391   region->init_req(2, src_dest_conjoint);
6392 
6393   record_for_igvn(region);
6394   return _gvn.transform(region);
6395 }
6396 
6397 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
6398 // Return node representing slow path of predicate check.
6399 // the pseudo code we want to emulate with this predicate is:
6400 // for encryption:
6401 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6402 // for decryption:
6403 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6404 //    note cipher==plain is more conservative than the original java code but that's OK
6405 //
6406 
6407 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
6408   // The receiver was checked for NULL already.
6409   Node* objCTR = argument(0);
6410 
6411   // Load embeddedCipher field of CipherBlockChaining object.
6412   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
6413 
6414   // get AESCrypt klass for instanceOf check
6415   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6416   // will have same classloader as CipherBlockChaining object
6417   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
6418   assert(tinst != NULL, "CTRobj is null");
6419   assert(tinst->klass()->is_loaded(), "CTRobj is not loaded");
6420 
6421   // we want to do an instanceof comparison against the AESCrypt class
6422   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6423   if (!klass_AESCrypt->is_loaded()) {
6424     // if AESCrypt is not even loaded, we never take the intrinsic fast path
6425     Node* ctrl = control();
6426     set_control(top()); // no regular fast path
6427     return ctrl;
6428   }
6429 
6430   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6431   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6432   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6433   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6434   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6435 
6436   return instof_false; // even if it is NULL
6437 }
6438 
6439 //------------------------------inline_ghash_processBlocks
6440 bool LibraryCallKit::inline_ghash_processBlocks() {
6441   address stubAddr;
6442   const char *stubName;
6443   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6444 
6445   stubAddr = StubRoutines::ghash_processBlocks();
6446   stubName = "ghash_processBlocks";
6447 
6448   Node* data           = argument(0);
6449   Node* offset         = argument(1);
6450   Node* len            = argument(2);
6451   Node* state          = argument(3);
6452   Node* subkeyH        = argument(4);
6453 
6454   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
6455   assert(state_start, "state is NULL");
6456   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
6457   assert(subkeyH_start, "subkeyH is NULL");
6458   Node* data_start  = array_element_address(data, offset, T_BYTE);
6459   assert(data_start, "data is NULL");
6460 
6461   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6462                                   OptoRuntime::ghash_processBlocks_Type(),
6463                                   stubAddr, stubName, TypePtr::BOTTOM,
6464                                   state_start, subkeyH_start, data_start, len);
6465   return true;
6466 }
6467 
6468 //------------------------------inline_sha_implCompress-----------------------
6469 //
6470 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6471 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6472 //
6473 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6474 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6475 //
6476 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6477 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6478 //
6479 bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
6480   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6481 
6482   Node* sha_obj = argument(0);
6483   Node* src     = argument(1); // type oop
6484   Node* ofs     = argument(2); // type int
6485 
6486   const Type* src_type = src->Value(&_gvn);
6487   const TypeAryPtr* top_src = src_type->isa_aryptr();
6488   if (top_src  == NULL || top_src->klass()  == NULL) {
6489     // failed array check
6490     return false;
6491   }
6492   // Figure out the size and type of the elements we will be copying.
6493   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6494   if (src_elem != T_BYTE) {
6495     return false;
6496   }
6497   // 'src_start' points to src array + offset
6498   Node* src_start = array_element_address(src, ofs, src_elem);
6499   Node* state = NULL;
6500   address stubAddr;
6501   const char *stubName;
6502 
6503   switch(id) {
6504   case vmIntrinsics::_sha_implCompress:
6505     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6506     state = get_state_from_sha_object(sha_obj);
6507     stubAddr = StubRoutines::sha1_implCompress();
6508     stubName = "sha1_implCompress";
6509     break;
6510   case vmIntrinsics::_sha2_implCompress:
6511     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6512     state = get_state_from_sha_object(sha_obj);
6513     stubAddr = StubRoutines::sha256_implCompress();
6514     stubName = "sha256_implCompress";
6515     break;
6516   case vmIntrinsics::_sha5_implCompress:
6517     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6518     state = get_state_from_sha5_object(sha_obj);
6519     stubAddr = StubRoutines::sha512_implCompress();
6520     stubName = "sha512_implCompress";
6521     break;
6522   default:
6523     fatal_unexpected_iid(id);
6524     return false;
6525   }
6526   if (state == NULL) return false;
6527 
6528   // Call the stub.
6529   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
6530                                  stubAddr, stubName, TypePtr::BOTTOM,
6531                                  src_start, state);
6532 
6533   return true;
6534 }
6535 
6536 //------------------------------inline_digestBase_implCompressMB-----------------------
6537 //
6538 // Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
6539 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6540 //
6541 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6542   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6543          "need SHA1/SHA256/SHA512 instruction support");
6544   assert((uint)predicate < 3, "sanity");
6545   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6546 
6547   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6548   Node* src            = argument(1); // byte[] array
6549   Node* ofs            = argument(2); // type int
6550   Node* limit          = argument(3); // type int
6551 
6552   const Type* src_type = src->Value(&_gvn);
6553   const TypeAryPtr* top_src = src_type->isa_aryptr();
6554   if (top_src  == NULL || top_src->klass()  == NULL) {
6555     // failed array check
6556     return false;
6557   }
6558   // Figure out the size and type of the elements we will be copying.
6559   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6560   if (src_elem != T_BYTE) {
6561     return false;
6562   }
6563   // 'src_start' points to src array + offset
6564   Node* src_start = array_element_address(src, ofs, src_elem);
6565 
6566   const char* klass_SHA_name = NULL;
6567   const char* stub_name = NULL;
6568   address     stub_addr = NULL;
6569   bool        long_state = false;
6570 
6571   switch (predicate) {
6572   case 0:
6573     if (UseSHA1Intrinsics) {
6574       klass_SHA_name = "sun/security/provider/SHA";
6575       stub_name = "sha1_implCompressMB";
6576       stub_addr = StubRoutines::sha1_implCompressMB();
6577     }
6578     break;
6579   case 1:
6580     if (UseSHA256Intrinsics) {
6581       klass_SHA_name = "sun/security/provider/SHA2";
6582       stub_name = "sha256_implCompressMB";
6583       stub_addr = StubRoutines::sha256_implCompressMB();
6584     }
6585     break;
6586   case 2:
6587     if (UseSHA512Intrinsics) {
6588       klass_SHA_name = "sun/security/provider/SHA5";
6589       stub_name = "sha512_implCompressMB";
6590       stub_addr = StubRoutines::sha512_implCompressMB();
6591       long_state = true;
6592     }
6593     break;
6594   default:
6595     fatal("unknown SHA intrinsic predicate: %d", predicate);
6596   }
6597   if (klass_SHA_name != NULL) {
6598     // get DigestBase klass to lookup for SHA klass
6599     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
6600     assert(tinst != NULL, "digestBase_obj is not instance???");
6601     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6602 
6603     ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6604     assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
6605     ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6606     return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
6607   }
6608   return false;
6609 }
6610 //------------------------------inline_sha_implCompressMB-----------------------
6611 bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
6612                                                bool long_state, address stubAddr, const char *stubName,
6613                                                Node* src_start, Node* ofs, Node* limit) {
6614   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
6615   const TypeOopPtr* xtype = aklass->as_instance_type();
6616   Node* sha_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
6617   sha_obj = _gvn.transform(sha_obj);
6618 
6619   Node* state;
6620   if (long_state) {
6621     state = get_state_from_sha5_object(sha_obj);
6622   } else {
6623     state = get_state_from_sha_object(sha_obj);
6624   }
6625   if (state == NULL) return false;
6626 
6627   // Call the stub.
6628   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6629                                  OptoRuntime::digestBase_implCompressMB_Type(),
6630                                  stubAddr, stubName, TypePtr::BOTTOM,
6631                                  src_start, state, ofs, limit);
6632   // return ofs (int)
6633   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6634   set_result(result);
6635 
6636   return true;
6637 }
6638 
6639 //------------------------------get_state_from_sha_object-----------------------
6640 Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
6641   Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
6642   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
6643   if (sha_state == NULL) return (Node *) NULL;
6644 
6645   // now have the array, need to get the start address of the state array
6646   Node* state = array_element_address(sha_state, intcon(0), T_INT);
6647   return state;
6648 }
6649 
6650 //------------------------------get_state_from_sha5_object-----------------------
6651 Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
6652   Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
6653   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
6654   if (sha_state == NULL) return (Node *) NULL;
6655 
6656   // now have the array, need to get the start address of the state array
6657   Node* state = array_element_address(sha_state, intcon(0), T_LONG);
6658   return state;
6659 }
6660 
6661 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
6662 // Return node representing slow path of predicate check.
6663 // the pseudo code we want to emulate with this predicate is:
6664 //    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
6665 //
6666 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
6667   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
6668          "need SHA1/SHA256/SHA512 instruction support");
6669   assert((uint)predicate < 3, "sanity");
6670 
6671   // The receiver was checked for NULL already.
6672   Node* digestBaseObj = argument(0);
6673 
6674   // get DigestBase klass for instanceOf check
6675   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
6676   assert(tinst != NULL, "digestBaseObj is null");
6677   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6678 
6679   const char* klass_SHA_name = NULL;
6680   switch (predicate) {
6681   case 0:
6682     if (UseSHA1Intrinsics) {
6683       // we want to do an instanceof comparison against the SHA class
6684       klass_SHA_name = "sun/security/provider/SHA";
6685     }
6686     break;
6687   case 1:
6688     if (UseSHA256Intrinsics) {
6689       // we want to do an instanceof comparison against the SHA2 class
6690       klass_SHA_name = "sun/security/provider/SHA2";
6691     }
6692     break;
6693   case 2:
6694     if (UseSHA512Intrinsics) {
6695       // we want to do an instanceof comparison against the SHA5 class
6696       klass_SHA_name = "sun/security/provider/SHA5";
6697     }
6698     break;
6699   default:
6700     fatal("unknown SHA intrinsic predicate: %d", predicate);
6701   }
6702 
6703   ciKlass* klass_SHA = NULL;
6704   if (klass_SHA_name != NULL) {
6705     klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
6706   }
6707   if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
6708     // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
6709     Node* ctrl = control();
6710     set_control(top()); // no intrinsic path
6711     return ctrl;
6712   }
6713   ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
6714 
6715   Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
6716   Node* cmp_instof = _gvn.transform(new CmpINode(instofSHA, intcon(1)));
6717   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6718   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6719 
6720   return instof_false;  // even if it is NULL
6721 }
6722 
6723 bool LibraryCallKit::inline_profileBoolean() {
6724   Node* counts = argument(1);
6725   const TypeAryPtr* ary = NULL;
6726   ciArray* aobj = NULL;
6727   if (counts->is_Con()
6728       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6729       && (aobj = ary->const_oop()->as_array()) != NULL
6730       && (aobj->length() == 2)) {
6731     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6732     jint false_cnt = aobj->element_value(0).as_int();
6733     jint  true_cnt = aobj->element_value(1).as_int();
6734 
6735     if (C->log() != NULL) {
6736       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6737                      false_cnt, true_cnt);
6738     }
6739 
6740     if (false_cnt + true_cnt == 0) {
6741       // According to profile, never executed.
6742       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6743                           Deoptimization::Action_reinterpret);
6744       return true;
6745     }
6746 
6747     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6748     // is a number of each value occurrences.
6749     Node* result = argument(0);
6750     if (false_cnt == 0 || true_cnt == 0) {
6751       // According to profile, one value has been never seen.
6752       int expected_val = (false_cnt == 0) ? 1 : 0;
6753 
6754       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6755       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6756 
6757       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6758       Node* fast_path = _gvn.transform(new IfTrueNode(check));
6759       Node* slow_path = _gvn.transform(new IfFalseNode(check));
6760 
6761       { // Slow path: uncommon trap for never seen value and then reexecute
6762         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6763         // the value has been seen at least once.
6764         PreserveJVMState pjvms(this);
6765         PreserveReexecuteState preexecs(this);
6766         jvms()->set_should_reexecute(true);
6767 
6768         set_control(slow_path);
6769         set_i_o(i_o());
6770 
6771         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6772                             Deoptimization::Action_reinterpret);
6773       }
6774       // The guard for never seen value enables sharpening of the result and
6775       // returning a constant. It allows to eliminate branches on the same value
6776       // later on.
6777       set_control(fast_path);
6778       result = intcon(expected_val);
6779     }
6780     // Stop profiling.
6781     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6782     // By replacing method body with profile data (represented as ProfileBooleanNode
6783     // on IR level) we effectively disable profiling.
6784     // It enables full speed execution once optimized code is generated.
6785     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6786     C->record_for_igvn(profile);
6787     set_result(profile);
6788     return true;
6789   } else {
6790     // Continue profiling.
6791     // Profile data isn't available at the moment. So, execute method's bytecode version.
6792     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6793     // is compiled and counters aren't available since corresponding MethodHandle
6794     // isn't a compile-time constant.
6795     return false;
6796   }
6797 }
6798 
6799 bool LibraryCallKit::inline_isCompileConstant() {
6800   Node* n = argument(0);
6801   set_result(n->is_Con() ? intcon(1) : intcon(0));
6802   return true;
6803 }
6804 
6805 bool LibraryCallKit::inline_deoptimize() {
6806   assert(WhiteBoxAPI, "");
6807   PreserveReexecuteState preexecs(this);
6808   jvms()->set_should_reexecute(false);
6809   uncommon_trap(Deoptimization::Reason_intrinsic,
6810                 Deoptimization::Action_none);
6811   return true;
6812 }