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