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