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