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