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