rev 7390 : 8028595: WhiteBox API for stress testing of TieredCompilation
Reviewed-by:

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