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