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