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