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