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