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