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