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