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