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