src/share/vm/opto/library_call.cpp

Tue, 10 Mar 2020 10:46:35 +0100

author
mdoerr
date
Tue, 10 Mar 2020 10:46:35 +0100
changeset 9912
97d09139b360
parent 9896
1b8c45b8216a
child 9931
fd44df5e3bc3
permissions
-rw-r--r--

8146612: C2: Precedence edges specification violated
Reviewed-by: kvn

     1 /*
     2  * Copyright (c) 1999, 2019, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/systemDictionary.hpp"
    27 #include "classfile/vmSymbols.hpp"
    28 #include "compiler/compileBroker.hpp"
    29 #include "compiler/compileLog.hpp"
    30 #include "jfr/support/jfrIntrinsics.hpp"
    31 #include "oops/objArrayKlass.hpp"
    32 #include "opto/addnode.hpp"
    33 #include "opto/callGenerator.hpp"
    34 #include "opto/cfgnode.hpp"
    35 #include "opto/connode.hpp"
    36 #include "opto/idealKit.hpp"
    37 #include "opto/mathexactnode.hpp"
    38 #include "opto/mulnode.hpp"
    39 #include "opto/parse.hpp"
    40 #include "opto/runtime.hpp"
    41 #include "opto/subnode.hpp"
    42 #include "prims/nativeLookup.hpp"
    43 #include "runtime/sharedRuntime.hpp"
    44 #include "utilities/macros.hpp"
    46 class LibraryIntrinsic : public InlineCallGenerator {
    47   // Extend the set of intrinsics known to the runtime:
    48  public:
    49  private:
    50   bool             _is_virtual;
    51   bool             _does_virtual_dispatch;
    52   int8_t           _predicates_count;  // Intrinsic is predicated by several conditions
    53   int8_t           _last_predicate; // Last generated predicate
    54   vmIntrinsics::ID _intrinsic_id;
    56  public:
    57   LibraryIntrinsic(ciMethod* m, bool is_virtual, int predicates_count, bool does_virtual_dispatch, vmIntrinsics::ID id)
    58     : InlineCallGenerator(m),
    59       _is_virtual(is_virtual),
    60       _does_virtual_dispatch(does_virtual_dispatch),
    61       _predicates_count((int8_t)predicates_count),
    62       _last_predicate((int8_t)-1),
    63       _intrinsic_id(id)
    64   {
    65   }
    66   virtual bool is_intrinsic() const { return true; }
    67   virtual bool is_virtual()   const { return _is_virtual; }
    68   virtual bool is_predicated() const { return _predicates_count > 0; }
    69   virtual int  predicates_count() const { return _predicates_count; }
    70   virtual bool does_virtual_dispatch()   const { return _does_virtual_dispatch; }
    71   virtual JVMState* generate(JVMState* jvms);
    72   virtual Node* generate_predicate(JVMState* jvms, int predicate);
    73   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
    74 };
    77 // Local helper class for LibraryIntrinsic:
    78 class LibraryCallKit : public GraphKit {
    79  private:
    80   LibraryIntrinsic* _intrinsic;     // the library intrinsic being called
    81   Node*             _result;        // the result node, if any
    82   int               _reexecute_sp;  // the stack pointer when bytecode needs to be reexecuted
    84   const TypeOopPtr* sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr = false);
    86  public:
    87   LibraryCallKit(JVMState* jvms, LibraryIntrinsic* intrinsic)
    88     : GraphKit(jvms),
    89       _intrinsic(intrinsic),
    90       _result(NULL)
    91   {
    92     // Check if this is a root compile.  In that case we don't have a caller.
    93     if (!jvms->has_method()) {
    94       _reexecute_sp = sp();
    95     } else {
    96       // Find out how many arguments the interpreter needs when deoptimizing
    97       // and save the stack pointer value so it can used by uncommon_trap.
    98       // We find the argument count by looking at the declared signature.
    99       bool ignored_will_link;
   100       ciSignature* declared_signature = NULL;
   101       ciMethod* ignored_callee = caller()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
   102       const int nargs = declared_signature->arg_size_for_bc(caller()->java_code_at_bci(bci()));
   103       _reexecute_sp = sp() + nargs;  // "push" arguments back on stack
   104     }
   105   }
   107   virtual LibraryCallKit* is_LibraryCallKit() const { return (LibraryCallKit*)this; }
   109   ciMethod*         caller()    const    { return jvms()->method(); }
   110   int               bci()       const    { return jvms()->bci(); }
   111   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
   112   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
   113   ciMethod*         callee()    const    { return _intrinsic->method(); }
   115   bool  try_to_inline(int predicate);
   116   Node* try_to_predicate(int predicate);
   118   void push_result() {
   119     // Push the result onto the stack.
   120     if (!stopped() && result() != NULL) {
   121       BasicType bt = result()->bottom_type()->basic_type();
   122       push_node(bt, result());
   123     }
   124   }
   126  private:
   127   void fatal_unexpected_iid(vmIntrinsics::ID iid) {
   128     fatal(err_msg_res("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid)));
   129   }
   131   void  set_result(Node* n) { assert(_result == NULL, "only set once"); _result = n; }
   132   void  set_result(RegionNode* region, PhiNode* value);
   133   Node*     result() { return _result; }
   135   virtual int reexecute_sp() { return _reexecute_sp; }
   137   // Helper functions to inline natives
   138   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
   139   Node* generate_slow_guard(Node* test, RegionNode* region);
   140   Node* generate_fair_guard(Node* test, RegionNode* region);
   141   Node* generate_negative_guard(Node* index, RegionNode* region,
   142                                 // resulting CastII of index:
   143                                 Node* *pos_index = NULL);
   144   Node* generate_nonpositive_guard(Node* index, bool never_negative,
   145                                    // resulting CastII of index:
   146                                    Node* *pos_index = NULL);
   147   Node* generate_limit_guard(Node* offset, Node* subseq_length,
   148                              Node* array_length,
   149                              RegionNode* region);
   150   Node* generate_current_thread(Node* &tls_output);
   151   address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,
   152                               bool disjoint_bases, const char* &name, bool dest_uninitialized);
   153   Node* load_mirror_from_klass(Node* klass);
   154   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
   155                                       RegionNode* region, int null_path,
   156                                       int offset);
   157   Node* load_klass_from_mirror(Node* mirror, bool never_see_null,
   158                                RegionNode* region, int null_path) {
   159     int offset = java_lang_Class::klass_offset_in_bytes();
   160     return load_klass_from_mirror_common(mirror, never_see_null,
   161                                          region, null_path,
   162                                          offset);
   163   }
   164   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
   165                                      RegionNode* region, int null_path) {
   166     int offset = java_lang_Class::array_klass_offset_in_bytes();
   167     return load_klass_from_mirror_common(mirror, never_see_null,
   168                                          region, null_path,
   169                                          offset);
   170   }
   171   Node* generate_access_flags_guard(Node* kls,
   172                                     int modifier_mask, int modifier_bits,
   173                                     RegionNode* region);
   174   Node* generate_interface_guard(Node* kls, RegionNode* region);
   175   Node* generate_array_guard(Node* kls, RegionNode* region) {
   176     return generate_array_guard_common(kls, region, false, false);
   177   }
   178   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
   179     return generate_array_guard_common(kls, region, false, true);
   180   }
   181   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
   182     return generate_array_guard_common(kls, region, true, false);
   183   }
   184   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
   185     return generate_array_guard_common(kls, region, true, true);
   186   }
   187   Node* generate_array_guard_common(Node* kls, RegionNode* region,
   188                                     bool obj_array, bool not_array);
   189   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
   190   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
   191                                      bool is_virtual = false, bool is_static = false);
   192   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
   193     return generate_method_call(method_id, false, true);
   194   }
   195   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
   196     return generate_method_call(method_id, true, false);
   197   }
   198   Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static);
   200   Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2);
   201   Node* make_string_method_node(int opcode, Node* str1, Node* str2);
   202   bool inline_string_compareTo();
   203   bool inline_string_indexOf();
   204   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
   205   bool inline_string_equals();
   206   Node* round_double_node(Node* n);
   207   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
   208   bool inline_math_native(vmIntrinsics::ID id);
   209   bool inline_trig(vmIntrinsics::ID id);
   210   bool inline_math(vmIntrinsics::ID id);
   211   template <typename OverflowOp>
   212   bool inline_math_overflow(Node* arg1, Node* arg2);
   213   void inline_math_mathExact(Node* math, Node* test);
   214   bool inline_math_addExactI(bool is_increment);
   215   bool inline_math_addExactL(bool is_increment);
   216   bool inline_math_multiplyExactI();
   217   bool inline_math_multiplyExactL();
   218   bool inline_math_negateExactI();
   219   bool inline_math_negateExactL();
   220   bool inline_math_subtractExactI(bool is_decrement);
   221   bool inline_math_subtractExactL(bool is_decrement);
   222   bool inline_exp();
   223   bool inline_pow();
   224   Node* finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName);
   225   bool inline_min_max(vmIntrinsics::ID id);
   226   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
   227   // This returns Type::AnyPtr, RawPtr, or OopPtr.
   228   int classify_unsafe_addr(Node* &base, Node* &offset);
   229   Node* make_unsafe_address(Node* base, Node* offset);
   230   // Helper for inline_unsafe_access.
   231   // Generates the guards that check whether the result of
   232   // Unsafe.getObject should be recorded in an SATB log buffer.
   233   void insert_pre_barrier(Node* base_oop, Node* offset, Node* pre_val, bool need_mem_bar);
   234   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool is_unaligned);
   235   bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
   236   static bool klass_needs_init_guard(Node* kls);
   237   bool inline_unsafe_allocate();
   238   bool inline_unsafe_copyMemory();
   239   bool inline_native_currentThread();
   240 #ifdef JFR_HAVE_INTRINSICS
   241   bool inline_native_classID();
   242   bool inline_native_getEventWriter();
   243 #endif
   244   bool inline_native_time_funcs(address method, const char* funcName);
   245   bool inline_native_isInterrupted();
   246   bool inline_native_Class_query(vmIntrinsics::ID id);
   247   bool inline_native_subtype_check();
   249   bool inline_native_newArray();
   250   bool inline_native_getLength();
   251   bool inline_array_copyOf(bool is_copyOfRange);
   252   bool inline_array_equals();
   253   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
   254   bool inline_native_clone(bool is_virtual);
   255   bool inline_native_Reflection_getCallerClass();
   256   // Helper function for inlining native object hash method
   257   bool inline_native_hashcode(bool is_virtual, bool is_static);
   258   bool inline_native_getClass();
   260   // Helper functions for inlining arraycopy
   261   bool inline_arraycopy();
   262   void generate_arraycopy(const TypePtr* adr_type,
   263                           BasicType basic_elem_type,
   264                           Node* src,  Node* src_offset,
   265                           Node* dest, Node* dest_offset,
   266                           Node* copy_length,
   267                           bool disjoint_bases = false,
   268                           bool length_never_negative = false,
   269                           RegionNode* slow_region = NULL);
   270   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
   271                                                 RegionNode* slow_region);
   272   void generate_clear_array(const TypePtr* adr_type,
   273                             Node* dest,
   274                             BasicType basic_elem_type,
   275                             Node* slice_off,
   276                             Node* slice_len,
   277                             Node* slice_end);
   278   bool generate_block_arraycopy(const TypePtr* adr_type,
   279                                 BasicType basic_elem_type,
   280                                 AllocateNode* alloc,
   281                                 Node* src,  Node* src_offset,
   282                                 Node* dest, Node* dest_offset,
   283                                 Node* dest_size, bool dest_uninitialized);
   284   void generate_slow_arraycopy(const TypePtr* adr_type,
   285                                Node* src,  Node* src_offset,
   286                                Node* dest, Node* dest_offset,
   287                                Node* copy_length, bool dest_uninitialized);
   288   Node* generate_checkcast_arraycopy(const TypePtr* adr_type,
   289                                      Node* dest_elem_klass,
   290                                      Node* src,  Node* src_offset,
   291                                      Node* dest, Node* dest_offset,
   292                                      Node* copy_length, bool dest_uninitialized);
   293   Node* generate_generic_arraycopy(const TypePtr* adr_type,
   294                                    Node* src,  Node* src_offset,
   295                                    Node* dest, Node* dest_offset,
   296                                    Node* copy_length, bool dest_uninitialized);
   297   void generate_unchecked_arraycopy(const TypePtr* adr_type,
   298                                     BasicType basic_elem_type,
   299                                     bool disjoint_bases,
   300                                     Node* src,  Node* src_offset,
   301                                     Node* dest, Node* dest_offset,
   302                                     Node* copy_length, bool dest_uninitialized);
   303   typedef enum { LS_xadd, LS_xchg, LS_cmpxchg } LoadStoreKind;
   304   bool inline_unsafe_load_store(BasicType type,  LoadStoreKind kind);
   305   bool inline_unsafe_ordered_store(BasicType type);
   306   bool inline_unsafe_fence(vmIntrinsics::ID id);
   307   bool inline_fp_conversions(vmIntrinsics::ID id);
   308   bool inline_number_methods(vmIntrinsics::ID id);
   309   bool inline_reference_get();
   310   bool inline_aescrypt_Block(vmIntrinsics::ID id);
   311   bool inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id);
   312   Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting);
   313   Node* get_key_start_from_aescrypt_object(Node* aescrypt_object);
   314   Node* get_original_key_start_from_aescrypt_object(Node* aescrypt_object);
   315   bool inline_ghash_processBlocks();
   316   bool inline_sha_implCompress(vmIntrinsics::ID id);
   317   bool inline_digestBase_implCompressMB(int predicate);
   318   bool inline_sha_implCompressMB(Node* digestBaseObj, ciInstanceKlass* instklass_SHA,
   319                                  bool long_state, address stubAddr, const char *stubName,
   320                                  Node* src_start, Node* ofs, Node* limit);
   321   Node* get_state_from_sha_object(Node *sha_object);
   322   Node* get_state_from_sha5_object(Node *sha_object);
   323   Node* inline_digestBase_implCompressMB_predicate(int predicate);
   324   bool inline_encodeISOArray();
   325   bool inline_updateCRC32();
   326   bool inline_updateBytesCRC32();
   327   bool inline_updateByteBufferCRC32();
   328   bool inline_multiplyToLen();
   329   bool inline_squareToLen();
   330   bool inline_mulAdd();
   331   bool inline_montgomeryMultiply();
   332   bool inline_montgomerySquare();
   334   bool inline_profileBoolean();
   335 };
   338 //---------------------------make_vm_intrinsic----------------------------
   339 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
   340   vmIntrinsics::ID id = m->intrinsic_id();
   341   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
   343   ccstr disable_intr = NULL;
   345   if ((DisableIntrinsic[0] != '\0'
   346        && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) ||
   347       (method_has_option_value("DisableIntrinsic", disable_intr)
   348        && strstr(disable_intr, vmIntrinsics::name_at(id)) != NULL)) {
   349     // disabled by a user request on the command line:
   350     // example: -XX:DisableIntrinsic=_hashCode,_getClass
   351     return NULL;
   352   }
   354   if (!m->is_loaded()) {
   355     // do not attempt to inline unloaded methods
   356     return NULL;
   357   }
   359   // Only a few intrinsics implement a virtual dispatch.
   360   // They are expensive calls which are also frequently overridden.
   361   if (is_virtual) {
   362     switch (id) {
   363     case vmIntrinsics::_hashCode:
   364     case vmIntrinsics::_clone:
   365       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
   366       break;
   367     default:
   368       return NULL;
   369     }
   370   }
   372   // -XX:-InlineNatives disables nearly all intrinsics:
   373   if (!InlineNatives) {
   374     switch (id) {
   375     case vmIntrinsics::_indexOf:
   376     case vmIntrinsics::_compareTo:
   377     case vmIntrinsics::_equals:
   378     case vmIntrinsics::_equalsC:
   379     case vmIntrinsics::_getAndAddInt:
   380     case vmIntrinsics::_getAndAddLong:
   381     case vmIntrinsics::_getAndSetInt:
   382     case vmIntrinsics::_getAndSetLong:
   383     case vmIntrinsics::_getAndSetObject:
   384     case vmIntrinsics::_loadFence:
   385     case vmIntrinsics::_storeFence:
   386     case vmIntrinsics::_fullFence:
   387       break;  // InlineNatives does not control String.compareTo
   388     case vmIntrinsics::_Reference_get:
   389       break;  // InlineNatives does not control Reference.get
   390     default:
   391       return NULL;
   392     }
   393   }
   395   int predicates = 0;
   396   bool does_virtual_dispatch = false;
   398   switch (id) {
   399   case vmIntrinsics::_compareTo:
   400     if (!SpecialStringCompareTo)  return NULL;
   401     if (!Matcher::match_rule_supported(Op_StrComp))  return NULL;
   402     break;
   403   case vmIntrinsics::_indexOf:
   404     if (!SpecialStringIndexOf)  return NULL;
   405     break;
   406   case vmIntrinsics::_equals:
   407     if (!SpecialStringEquals)  return NULL;
   408     if (!Matcher::match_rule_supported(Op_StrEquals))  return NULL;
   409     break;
   410   case vmIntrinsics::_equalsC:
   411     if (!SpecialArraysEquals)  return NULL;
   412     if (!Matcher::match_rule_supported(Op_AryEq))  return NULL;
   413     break;
   414   case vmIntrinsics::_arraycopy:
   415     if (!InlineArrayCopy)  return NULL;
   416     break;
   417   case vmIntrinsics::_copyMemory:
   418     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
   419     if (!InlineArrayCopy)  return NULL;
   420     break;
   421   case vmIntrinsics::_hashCode:
   422     if (!InlineObjectHash)  return NULL;
   423     does_virtual_dispatch = true;
   424     break;
   425   case vmIntrinsics::_clone:
   426     does_virtual_dispatch = true;
   427   case vmIntrinsics::_copyOf:
   428   case vmIntrinsics::_copyOfRange:
   429     if (!InlineObjectCopy)  return NULL;
   430     // These also use the arraycopy intrinsic mechanism:
   431     if (!InlineArrayCopy)  return NULL;
   432     break;
   433   case vmIntrinsics::_encodeISOArray:
   434     if (!SpecialEncodeISOArray)  return NULL;
   435     if (!Matcher::match_rule_supported(Op_EncodeISOArray))  return NULL;
   436     break;
   437   case vmIntrinsics::_checkIndex:
   438     // We do not intrinsify this.  The optimizer does fine with it.
   439     return NULL;
   441   case vmIntrinsics::_getCallerClass:
   442     if (!UseNewReflection)  return NULL;
   443     if (!InlineReflectionGetCallerClass)  return NULL;
   444     if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
   445     break;
   447   case vmIntrinsics::_bitCount_i:
   448     if (!Matcher::match_rule_supported(Op_PopCountI)) return NULL;
   449     break;
   451   case vmIntrinsics::_bitCount_l:
   452     if (!Matcher::match_rule_supported(Op_PopCountL)) return NULL;
   453     break;
   455   case vmIntrinsics::_numberOfLeadingZeros_i:
   456     if (!Matcher::match_rule_supported(Op_CountLeadingZerosI)) return NULL;
   457     break;
   459   case vmIntrinsics::_numberOfLeadingZeros_l:
   460     if (!Matcher::match_rule_supported(Op_CountLeadingZerosL)) return NULL;
   461     break;
   463   case vmIntrinsics::_numberOfTrailingZeros_i:
   464     if (!Matcher::match_rule_supported(Op_CountTrailingZerosI)) return NULL;
   465     break;
   467   case vmIntrinsics::_numberOfTrailingZeros_l:
   468     if (!Matcher::match_rule_supported(Op_CountTrailingZerosL)) return NULL;
   469     break;
   471   case vmIntrinsics::_reverseBytes_c:
   472     if (!Matcher::match_rule_supported(Op_ReverseBytesUS)) return NULL;
   473     break;
   474   case vmIntrinsics::_reverseBytes_s:
   475     if (!Matcher::match_rule_supported(Op_ReverseBytesS))  return NULL;
   476     break;
   477   case vmIntrinsics::_reverseBytes_i:
   478     if (!Matcher::match_rule_supported(Op_ReverseBytesI))  return NULL;
   479     break;
   480   case vmIntrinsics::_reverseBytes_l:
   481     if (!Matcher::match_rule_supported(Op_ReverseBytesL))  return NULL;
   482     break;
   484   case vmIntrinsics::_Reference_get:
   485     // Use the intrinsic version of Reference.get() so that the value in
   486     // the referent field can be registered by the G1 pre-barrier code.
   487     // Also add memory barrier to prevent commoning reads from this field
   488     // across safepoint since GC can change it value.
   489     break;
   491   case vmIntrinsics::_compareAndSwapObject:
   492 #ifdef _LP64
   493     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_CompareAndSwapP)) return NULL;
   494 #endif
   495     break;
   497   case vmIntrinsics::_compareAndSwapLong:
   498     if (!Matcher::match_rule_supported(Op_CompareAndSwapL)) return NULL;
   499     break;
   501   case vmIntrinsics::_getAndAddInt:
   502     if (!Matcher::match_rule_supported(Op_GetAndAddI)) return NULL;
   503     break;
   505   case vmIntrinsics::_getAndAddLong:
   506     if (!Matcher::match_rule_supported(Op_GetAndAddL)) return NULL;
   507     break;
   509   case vmIntrinsics::_getAndSetInt:
   510     if (!Matcher::match_rule_supported(Op_GetAndSetI)) return NULL;
   511     break;
   513   case vmIntrinsics::_getAndSetLong:
   514     if (!Matcher::match_rule_supported(Op_GetAndSetL)) return NULL;
   515     break;
   517   case vmIntrinsics::_getAndSetObject:
   518 #ifdef _LP64
   519     if (!UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
   520     if (UseCompressedOops && !Matcher::match_rule_supported(Op_GetAndSetN)) return NULL;
   521     break;
   522 #else
   523     if (!Matcher::match_rule_supported(Op_GetAndSetP)) return NULL;
   524     break;
   525 #endif
   527   case vmIntrinsics::_aescrypt_encryptBlock:
   528   case vmIntrinsics::_aescrypt_decryptBlock:
   529     if (!UseAESIntrinsics) return NULL;
   530     break;
   532   case vmIntrinsics::_multiplyToLen:
   533     if (!UseMultiplyToLenIntrinsic) return NULL;
   534     break;
   536   case vmIntrinsics::_squareToLen:
   537     if (!UseSquareToLenIntrinsic) return NULL;
   538     break;
   540   case vmIntrinsics::_mulAdd:
   541     if (!UseMulAddIntrinsic) return NULL;
   542     break;
   544   case vmIntrinsics::_montgomeryMultiply:
   545      if (!UseMontgomeryMultiplyIntrinsic) return NULL;
   546     break;
   547   case vmIntrinsics::_montgomerySquare:
   548      if (!UseMontgomerySquareIntrinsic) return NULL;
   549     break;
   551   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
   552   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
   553     if (!UseAESIntrinsics) return NULL;
   554     // these two require the predicated logic
   555     predicates = 1;
   556     break;
   558   case vmIntrinsics::_sha_implCompress:
   559     if (!UseSHA1Intrinsics) return NULL;
   560     break;
   562   case vmIntrinsics::_sha2_implCompress:
   563     if (!UseSHA256Intrinsics) return NULL;
   564     break;
   566   case vmIntrinsics::_sha5_implCompress:
   567     if (!UseSHA512Intrinsics) return NULL;
   568     break;
   570   case vmIntrinsics::_digestBase_implCompressMB:
   571     if (!(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics)) return NULL;
   572     predicates = 3;
   573     break;
   575   case vmIntrinsics::_ghash_processBlocks:
   576     if (!UseGHASHIntrinsics) return NULL;
   577     break;
   579   case vmIntrinsics::_updateCRC32:
   580   case vmIntrinsics::_updateBytesCRC32:
   581   case vmIntrinsics::_updateByteBufferCRC32:
   582     if (!UseCRC32Intrinsics) return NULL;
   583     break;
   585   case vmIntrinsics::_incrementExactI:
   586   case vmIntrinsics::_addExactI:
   587     if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL;
   588     break;
   589   case vmIntrinsics::_incrementExactL:
   590   case vmIntrinsics::_addExactL:
   591     if (!Matcher::match_rule_supported(Op_OverflowAddL) || !UseMathExactIntrinsics) return NULL;
   592     break;
   593   case vmIntrinsics::_decrementExactI:
   594   case vmIntrinsics::_subtractExactI:
   595     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
   596     break;
   597   case vmIntrinsics::_decrementExactL:
   598   case vmIntrinsics::_subtractExactL:
   599     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
   600     break;
   601   case vmIntrinsics::_negateExactI:
   602     if (!Matcher::match_rule_supported(Op_OverflowSubI) || !UseMathExactIntrinsics) return NULL;
   603     break;
   604   case vmIntrinsics::_negateExactL:
   605     if (!Matcher::match_rule_supported(Op_OverflowSubL) || !UseMathExactIntrinsics) return NULL;
   606     break;
   607   case vmIntrinsics::_multiplyExactI:
   608     if (!Matcher::match_rule_supported(Op_OverflowMulI) || !UseMathExactIntrinsics) return NULL;
   609     break;
   610   case vmIntrinsics::_multiplyExactL:
   611     if (!Matcher::match_rule_supported(Op_OverflowMulL) || !UseMathExactIntrinsics) return NULL;
   612     break;
   614  default:
   615     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
   616     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
   617     break;
   618   }
   620   // -XX:-InlineClassNatives disables natives from the Class class.
   621   // The flag applies to all reflective calls, notably Array.newArray
   622   // (visible to Java programmers as Array.newInstance).
   623   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
   624       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
   625     if (!InlineClassNatives)  return NULL;
   626   }
   628   // -XX:-InlineThreadNatives disables natives from the Thread class.
   629   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
   630     if (!InlineThreadNatives)  return NULL;
   631   }
   633   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
   634   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
   635       m->holder()->name() == ciSymbol::java_lang_Float() ||
   636       m->holder()->name() == ciSymbol::java_lang_Double()) {
   637     if (!InlineMathNatives)  return NULL;
   638   }
   640   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
   641   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
   642     if (!InlineUnsafeOps)  return NULL;
   643   }
   645   return new LibraryIntrinsic(m, is_virtual, predicates, does_virtual_dispatch, (vmIntrinsics::ID) id);
   646 }
   648 //----------------------register_library_intrinsics-----------------------
   649 // Initialize this file's data structures, for each Compile instance.
   650 void Compile::register_library_intrinsics() {
   651   // Nothing to do here.
   652 }
   654 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
   655   LibraryCallKit kit(jvms, this);
   656   Compile* C = kit.C;
   657   int nodes = C->unique();
   658 #ifndef PRODUCT
   659   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
   660     char buf[1000];
   661     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
   662     tty->print_cr("Intrinsic %s", str);
   663   }
   664 #endif
   665   ciMethod* callee = kit.callee();
   666   const int bci    = kit.bci();
   668   // Try to inline the intrinsic.
   669   if (kit.try_to_inline(_last_predicate)) {
   670     if (C->print_intrinsics() || C->print_inlining()) {
   671       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual)" : "(intrinsic)");
   672     }
   673     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
   674     if (C->log()) {
   675       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
   676                      vmIntrinsics::name_at(intrinsic_id()),
   677                      (is_virtual() ? " virtual='1'" : ""),
   678                      C->unique() - nodes);
   679     }
   680     // Push the result from the inlined method onto the stack.
   681     kit.push_result();
   682     return kit.transfer_exceptions_into_jvms();
   683   }
   685   // The intrinsic bailed out
   686   if (C->print_intrinsics() || C->print_inlining()) {
   687     if (jvms->has_method()) {
   688       // Not a root compile.
   689       const char* msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
   690       C->print_inlining(callee, jvms->depth() - 1, bci, msg);
   691     } else {
   692       // Root compile
   693       tty->print("Did not generate intrinsic %s%s at bci:%d in",
   694                vmIntrinsics::name_at(intrinsic_id()),
   695                (is_virtual() ? " (virtual)" : ""), bci);
   696     }
   697   }
   698   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
   699   return NULL;
   700 }
   702 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
   703   LibraryCallKit kit(jvms, this);
   704   Compile* C = kit.C;
   705   int nodes = C->unique();
   706   _last_predicate = predicate;
   707 #ifndef PRODUCT
   708   assert(is_predicated() && predicate < predicates_count(), "sanity");
   709   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
   710     char buf[1000];
   711     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
   712     tty->print_cr("Predicate for intrinsic %s", str);
   713   }
   714 #endif
   715   ciMethod* callee = kit.callee();
   716   const int bci    = kit.bci();
   718   Node* slow_ctl = kit.try_to_predicate(predicate);
   719   if (!kit.failing()) {
   720     if (C->print_intrinsics() || C->print_inlining()) {
   721       C->print_inlining(callee, jvms->depth() - 1, bci, is_virtual() ? "(intrinsic, virtual, predicate)" : "(intrinsic, predicate)");
   722     }
   723     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
   724     if (C->log()) {
   725       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
   726                      vmIntrinsics::name_at(intrinsic_id()),
   727                      (is_virtual() ? " virtual='1'" : ""),
   728                      C->unique() - nodes);
   729     }
   730     return slow_ctl; // Could be NULL if the check folds.
   731   }
   733   // The intrinsic bailed out
   734   if (C->print_intrinsics() || C->print_inlining()) {
   735     if (jvms->has_method()) {
   736       // Not a root compile.
   737       const char* msg = "failed to generate predicate for intrinsic";
   738       C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
   739     } else {
   740       // Root compile
   741       C->print_inlining_stream()->print("Did not generate predicate for intrinsic %s%s at bci:%d in",
   742                                         vmIntrinsics::name_at(intrinsic_id()),
   743                                         (is_virtual() ? " (virtual)" : ""), bci);
   744     }
   745   }
   746   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
   747   return NULL;
   748 }
   750 bool LibraryCallKit::try_to_inline(int predicate) {
   751   // Handle symbolic names for otherwise undistinguished boolean switches:
   752   const bool is_store       = true;
   753   const bool is_native_ptr  = true;
   754   const bool is_static      = true;
   755   const bool is_volatile    = true;
   757   if (!jvms()->has_method()) {
   758     // Root JVMState has a null method.
   759     assert(map()->memory()->Opcode() == Op_Parm, "");
   760     // Insert the memory aliasing node
   761     set_all_memory(reset_memory());
   762   }
   763   assert(merged_memory(), "");
   766   switch (intrinsic_id()) {
   767   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
   768   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
   769   case vmIntrinsics::_getClass:                 return inline_native_getClass();
   771   case vmIntrinsics::_dsin:
   772   case vmIntrinsics::_dcos:
   773   case vmIntrinsics::_dtan:
   774   case vmIntrinsics::_dabs:
   775   case vmIntrinsics::_datan2:
   776   case vmIntrinsics::_dsqrt:
   777   case vmIntrinsics::_dexp:
   778   case vmIntrinsics::_dlog:
   779   case vmIntrinsics::_dlog10:
   780   case vmIntrinsics::_dpow:                     return inline_math_native(intrinsic_id());
   782   case vmIntrinsics::_min:
   783   case vmIntrinsics::_max:                      return inline_min_max(intrinsic_id());
   785   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
   786   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
   787   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
   788   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
   789   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
   790   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
   791   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
   792   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
   793   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
   794   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
   795   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
   796   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
   798   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
   800   case vmIntrinsics::_compareTo:                return inline_string_compareTo();
   801   case vmIntrinsics::_indexOf:                  return inline_string_indexOf();
   802   case vmIntrinsics::_equals:                   return inline_string_equals();
   804   case vmIntrinsics::_getObject:                return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,  !is_volatile, false);
   805   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, !is_volatile, false);
   806   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,    !is_volatile, false);
   807   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,   !is_volatile, false);
   808   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,    !is_volatile, false);
   809   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,     !is_volatile, false);
   810   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,    !is_volatile, false);
   811   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,   !is_volatile, false);
   812   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,  !is_volatile, false);
   814   case vmIntrinsics::_putObject:                return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,  !is_volatile, false);
   815   case vmIntrinsics::_putBoolean:               return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN, !is_volatile, false);
   816   case vmIntrinsics::_putByte:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,    !is_volatile, false);
   817   case vmIntrinsics::_putShort:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,   !is_volatile, false);
   818   case vmIntrinsics::_putChar:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,    !is_volatile, false);
   819   case vmIntrinsics::_putInt:                   return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,     !is_volatile, false);
   820   case vmIntrinsics::_putLong:                  return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,    !is_volatile, false);
   821   case vmIntrinsics::_putFloat:                 return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,   !is_volatile, false);
   822   case vmIntrinsics::_putDouble:                return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,  !is_volatile, false);
   824   case vmIntrinsics::_getByte_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_BYTE,    !is_volatile, false);
   825   case vmIntrinsics::_getShort_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_SHORT,   !is_volatile, false);
   826   case vmIntrinsics::_getChar_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_CHAR,    !is_volatile, false);
   827   case vmIntrinsics::_getInt_raw:               return inline_unsafe_access( is_native_ptr, !is_store, T_INT,     !is_volatile, false);
   828   case vmIntrinsics::_getLong_raw:              return inline_unsafe_access( is_native_ptr, !is_store, T_LONG,    !is_volatile, false);
   829   case vmIntrinsics::_getFloat_raw:             return inline_unsafe_access( is_native_ptr, !is_store, T_FLOAT,   !is_volatile, false);
   830   case vmIntrinsics::_getDouble_raw:            return inline_unsafe_access( is_native_ptr, !is_store, T_DOUBLE,  !is_volatile, false);
   831   case vmIntrinsics::_getAddress_raw:           return inline_unsafe_access( is_native_ptr, !is_store, T_ADDRESS, !is_volatile, false);
   833   case vmIntrinsics::_putByte_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_BYTE,    !is_volatile, false);
   834   case vmIntrinsics::_putShort_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_SHORT,   !is_volatile, false);
   835   case vmIntrinsics::_putChar_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_CHAR,    !is_volatile, false);
   836   case vmIntrinsics::_putInt_raw:               return inline_unsafe_access( is_native_ptr,  is_store, T_INT,     !is_volatile, false);
   837   case vmIntrinsics::_putLong_raw:              return inline_unsafe_access( is_native_ptr,  is_store, T_LONG,    !is_volatile, false);
   838   case vmIntrinsics::_putFloat_raw:             return inline_unsafe_access( is_native_ptr,  is_store, T_FLOAT,   !is_volatile, false);
   839   case vmIntrinsics::_putDouble_raw:            return inline_unsafe_access( is_native_ptr,  is_store, T_DOUBLE,  !is_volatile, false);
   840   case vmIntrinsics::_putAddress_raw:           return inline_unsafe_access( is_native_ptr,  is_store, T_ADDRESS, !is_volatile, false);
   842   case vmIntrinsics::_getObjectVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT,   is_volatile, false);
   843   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN,  is_volatile, false);
   844   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE,     is_volatile, false);
   845   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT,    is_volatile, false);
   846   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR,     is_volatile, false);
   847   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_native_ptr, !is_store, T_INT,      is_volatile, false);
   848   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG,     is_volatile, false);
   849   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT,    is_volatile, false);
   850   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE,   is_volatile, false);
   852   case vmIntrinsics::_putObjectVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_OBJECT,   is_volatile, false);
   853   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access(!is_native_ptr,  is_store, T_BOOLEAN,  is_volatile, false);
   854   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_BYTE,     is_volatile, false);
   855   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_SHORT,    is_volatile, false);
   856   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_CHAR,     is_volatile, false);
   857   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access(!is_native_ptr,  is_store, T_INT,      is_volatile, false);
   858   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access(!is_native_ptr,  is_store, T_LONG,     is_volatile, false);
   859   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access(!is_native_ptr,  is_store, T_FLOAT,    is_volatile, false);
   860   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access(!is_native_ptr,  is_store, T_DOUBLE,   is_volatile, false);
   862   case vmIntrinsics::_prefetchRead:             return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
   863   case vmIntrinsics::_prefetchWrite:            return inline_unsafe_prefetch(!is_native_ptr,  is_store, !is_static);
   864   case vmIntrinsics::_prefetchReadStatic:       return inline_unsafe_prefetch(!is_native_ptr, !is_store,  is_static);
   865   case vmIntrinsics::_prefetchWriteStatic:      return inline_unsafe_prefetch(!is_native_ptr,  is_store,  is_static);
   867   case vmIntrinsics::_compareAndSwapObject:     return inline_unsafe_load_store(T_OBJECT, LS_cmpxchg);
   868   case vmIntrinsics::_compareAndSwapInt:        return inline_unsafe_load_store(T_INT,    LS_cmpxchg);
   869   case vmIntrinsics::_compareAndSwapLong:       return inline_unsafe_load_store(T_LONG,   LS_cmpxchg);
   871   case vmIntrinsics::_putOrderedObject:         return inline_unsafe_ordered_store(T_OBJECT);
   872   case vmIntrinsics::_putOrderedInt:            return inline_unsafe_ordered_store(T_INT);
   873   case vmIntrinsics::_putOrderedLong:           return inline_unsafe_ordered_store(T_LONG);
   875   case vmIntrinsics::_getAndAddInt:             return inline_unsafe_load_store(T_INT,    LS_xadd);
   876   case vmIntrinsics::_getAndAddLong:            return inline_unsafe_load_store(T_LONG,   LS_xadd);
   877   case vmIntrinsics::_getAndSetInt:             return inline_unsafe_load_store(T_INT,    LS_xchg);
   878   case vmIntrinsics::_getAndSetLong:            return inline_unsafe_load_store(T_LONG,   LS_xchg);
   879   case vmIntrinsics::_getAndSetObject:          return inline_unsafe_load_store(T_OBJECT, LS_xchg);
   881   case vmIntrinsics::_loadFence:
   882   case vmIntrinsics::_storeFence:
   883   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
   885   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
   886   case vmIntrinsics::_isInterrupted:            return inline_native_isInterrupted();
   888 #ifdef JFR_HAVE_INTRINSICS
   889   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");
   890   case vmIntrinsics::_getClassId:               return inline_native_classID();
   891   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
   892 #endif
   893   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
   894   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
   895   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
   896   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
   897   case vmIntrinsics::_newArray:                 return inline_native_newArray();
   898   case vmIntrinsics::_getLength:                return inline_native_getLength();
   899   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
   900   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
   901   case vmIntrinsics::_equalsC:                  return inline_array_equals();
   902   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
   904   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
   906   case vmIntrinsics::_isInstance:
   907   case vmIntrinsics::_getModifiers:
   908   case vmIntrinsics::_isInterface:
   909   case vmIntrinsics::_isArray:
   910   case vmIntrinsics::_isPrimitive:
   911   case vmIntrinsics::_getSuperclass:
   912   case vmIntrinsics::_getComponentType:
   913   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
   915   case vmIntrinsics::_floatToRawIntBits:
   916   case vmIntrinsics::_floatToIntBits:
   917   case vmIntrinsics::_intBitsToFloat:
   918   case vmIntrinsics::_doubleToRawLongBits:
   919   case vmIntrinsics::_doubleToLongBits:
   920   case vmIntrinsics::_longBitsToDouble:         return inline_fp_conversions(intrinsic_id());
   922   case vmIntrinsics::_numberOfLeadingZeros_i:
   923   case vmIntrinsics::_numberOfLeadingZeros_l:
   924   case vmIntrinsics::_numberOfTrailingZeros_i:
   925   case vmIntrinsics::_numberOfTrailingZeros_l:
   926   case vmIntrinsics::_bitCount_i:
   927   case vmIntrinsics::_bitCount_l:
   928   case vmIntrinsics::_reverseBytes_i:
   929   case vmIntrinsics::_reverseBytes_l:
   930   case vmIntrinsics::_reverseBytes_s:
   931   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
   933   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
   935   case vmIntrinsics::_Reference_get:            return inline_reference_get();
   937   case vmIntrinsics::_aescrypt_encryptBlock:
   938   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
   940   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
   941   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
   942     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
   944   case vmIntrinsics::_sha_implCompress:
   945   case vmIntrinsics::_sha2_implCompress:
   946   case vmIntrinsics::_sha5_implCompress:
   947     return inline_sha_implCompress(intrinsic_id());
   949   case vmIntrinsics::_digestBase_implCompressMB:
   950     return inline_digestBase_implCompressMB(predicate);
   952   case vmIntrinsics::_multiplyToLen:
   953     return inline_multiplyToLen();
   955   case vmIntrinsics::_squareToLen:
   956     return inline_squareToLen();
   958   case vmIntrinsics::_mulAdd:
   959     return inline_mulAdd();
   961   case vmIntrinsics::_montgomeryMultiply:
   962     return inline_montgomeryMultiply();
   963   case vmIntrinsics::_montgomerySquare:
   964     return inline_montgomerySquare();
   966   case vmIntrinsics::_ghash_processBlocks:
   967     return inline_ghash_processBlocks();
   969   case vmIntrinsics::_encodeISOArray:
   970     return inline_encodeISOArray();
   972   case vmIntrinsics::_updateCRC32:
   973     return inline_updateCRC32();
   974   case vmIntrinsics::_updateBytesCRC32:
   975     return inline_updateBytesCRC32();
   976   case vmIntrinsics::_updateByteBufferCRC32:
   977     return inline_updateByteBufferCRC32();
   979   case vmIntrinsics::_profileBoolean:
   980     return inline_profileBoolean();
   982   default:
   983     // If you get here, it may be that someone has added a new intrinsic
   984     // to the list in vmSymbols.hpp without implementing it here.
   985 #ifndef PRODUCT
   986     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
   987       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
   988                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
   989     }
   990 #endif
   991     return false;
   992   }
   993 }
   995 Node* LibraryCallKit::try_to_predicate(int predicate) {
   996   if (!jvms()->has_method()) {
   997     // Root JVMState has a null method.
   998     assert(map()->memory()->Opcode() == Op_Parm, "");
   999     // Insert the memory aliasing node
  1000     set_all_memory(reset_memory());
  1002   assert(merged_memory(), "");
  1004   switch (intrinsic_id()) {
  1005   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
  1006     return inline_cipherBlockChaining_AESCrypt_predicate(false);
  1007   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
  1008     return inline_cipherBlockChaining_AESCrypt_predicate(true);
  1009   case vmIntrinsics::_digestBase_implCompressMB:
  1010     return inline_digestBase_implCompressMB_predicate(predicate);
  1012   default:
  1013     // If you get here, it may be that someone has added a new intrinsic
  1014     // to the list in vmSymbols.hpp without implementing it here.
  1015 #ifndef PRODUCT
  1016     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
  1017       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
  1018                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
  1020 #endif
  1021     Node* slow_ctl = control();
  1022     set_control(top()); // No fast path instrinsic
  1023     return slow_ctl;
  1027 //------------------------------set_result-------------------------------
  1028 // Helper function for finishing intrinsics.
  1029 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
  1030   record_for_igvn(region);
  1031   set_control(_gvn.transform(region));
  1032   set_result( _gvn.transform(value));
  1033   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
  1036 //------------------------------generate_guard---------------------------
  1037 // Helper function for generating guarded fast-slow graph structures.
  1038 // The given 'test', if true, guards a slow path.  If the test fails
  1039 // then a fast path can be taken.  (We generally hope it fails.)
  1040 // In all cases, GraphKit::control() is updated to the fast path.
  1041 // The returned value represents the control for the slow path.
  1042 // The return value is never 'top'; it is either a valid control
  1043 // or NULL if it is obvious that the slow path can never be taken.
  1044 // Also, if region and the slow control are not NULL, the slow edge
  1045 // is appended to the region.
  1046 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
  1047   if (stopped()) {
  1048     // Already short circuited.
  1049     return NULL;
  1052   // Build an if node and its projections.
  1053   // If test is true we take the slow path, which we assume is uncommon.
  1054   if (_gvn.type(test) == TypeInt::ZERO) {
  1055     // The slow branch is never taken.  No need to build this guard.
  1056     return NULL;
  1059   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
  1061   Node* if_slow = _gvn.transform(new (C) IfTrueNode(iff));
  1062   if (if_slow == top()) {
  1063     // The slow branch is never taken.  No need to build this guard.
  1064     return NULL;
  1067   if (region != NULL)
  1068     region->add_req(if_slow);
  1070   Node* if_fast = _gvn.transform(new (C) IfFalseNode(iff));
  1071   set_control(if_fast);
  1073   return if_slow;
  1076 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
  1077   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
  1079 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
  1080   return generate_guard(test, region, PROB_FAIR);
  1083 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
  1084                                                      Node* *pos_index) {
  1085   if (stopped())
  1086     return NULL;                // already stopped
  1087   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
  1088     return NULL;                // index is already adequately typed
  1089   Node* cmp_lt = _gvn.transform(new (C) CmpINode(index, intcon(0)));
  1090   Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));
  1091   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
  1092   if (is_neg != NULL && pos_index != NULL) {
  1093     // Emulate effect of Parse::adjust_map_after_if.
  1094     Node* ccast = new (C) CastIINode(index, TypeInt::POS);
  1095     ccast->set_req(0, control());
  1096     (*pos_index) = _gvn.transform(ccast);
  1098   return is_neg;
  1101 inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,
  1102                                                         Node* *pos_index) {
  1103   if (stopped())
  1104     return NULL;                // already stopped
  1105   if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
  1106     return NULL;                // index is already adequately typed
  1107   Node* cmp_le = _gvn.transform(new (C) CmpINode(index, intcon(0)));
  1108   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
  1109   Node* bol_le = _gvn.transform(new (C) BoolNode(cmp_le, le_or_eq));
  1110   Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);
  1111   if (is_notp != NULL && pos_index != NULL) {
  1112     // Emulate effect of Parse::adjust_map_after_if.
  1113     Node* ccast = new (C) CastIINode(index, TypeInt::POS1);
  1114     ccast->set_req(0, control());
  1115     (*pos_index) = _gvn.transform(ccast);
  1117   return is_notp;
  1120 // Make sure that 'position' is a valid limit index, in [0..length].
  1121 // There are two equivalent plans for checking this:
  1122 //   A. (offset + copyLength)  unsigned<=  arrayLength
  1123 //   B. offset  <=  (arrayLength - copyLength)
  1124 // We require that all of the values above, except for the sum and
  1125 // difference, are already known to be non-negative.
  1126 // Plan A is robust in the face of overflow, if offset and copyLength
  1127 // are both hugely positive.
  1128 //
  1129 // Plan B is less direct and intuitive, but it does not overflow at
  1130 // all, since the difference of two non-negatives is always
  1131 // representable.  Whenever Java methods must perform the equivalent
  1132 // check they generally use Plan B instead of Plan A.
  1133 // For the moment we use Plan A.
  1134 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
  1135                                                   Node* subseq_length,
  1136                                                   Node* array_length,
  1137                                                   RegionNode* region) {
  1138   if (stopped())
  1139     return NULL;                // already stopped
  1140   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
  1141   if (zero_offset && subseq_length->eqv_uncast(array_length))
  1142     return NULL;                // common case of whole-array copy
  1143   Node* last = subseq_length;
  1144   if (!zero_offset)             // last += offset
  1145     last = _gvn.transform(new (C) AddINode(last, offset));
  1146   Node* cmp_lt = _gvn.transform(new (C) CmpUNode(array_length, last));
  1147   Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt));
  1148   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
  1149   return is_over;
  1153 //--------------------------generate_current_thread--------------------
  1154 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
  1155   ciKlass*    thread_klass = env()->Thread_klass();
  1156   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
  1157   Node* thread = _gvn.transform(new (C) ThreadLocalNode());
  1158   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
  1159   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT, MemNode::unordered);
  1160   tls_output = thread;
  1161   return threadObj;
  1165 //------------------------------make_string_method_node------------------------
  1166 // Helper method for String intrinsic functions. This version is called
  1167 // with str1 and str2 pointing to String object nodes.
  1168 //
  1169 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* str2) {
  1170   Node* no_ctrl = NULL;
  1172   // Get start addr of string
  1173   Node* str1_value   = load_String_value(no_ctrl, str1);
  1174   Node* str1_offset  = load_String_offset(no_ctrl, str1);
  1175   Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
  1177   // Get length of string 1
  1178   Node* str1_len  = load_String_length(no_ctrl, str1);
  1180   Node* str2_value   = load_String_value(no_ctrl, str2);
  1181   Node* str2_offset  = load_String_offset(no_ctrl, str2);
  1182   Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
  1184   Node* str2_len = NULL;
  1185   Node* result = NULL;
  1187   switch (opcode) {
  1188   case Op_StrIndexOf:
  1189     // Get length of string 2
  1190     str2_len = load_String_length(no_ctrl, str2);
  1192     result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
  1193                                  str1_start, str1_len, str2_start, str2_len);
  1194     break;
  1195   case Op_StrComp:
  1196     // Get length of string 2
  1197     str2_len = load_String_length(no_ctrl, str2);
  1199     result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),
  1200                                  str1_start, str1_len, str2_start, str2_len);
  1201     break;
  1202   case Op_StrEquals:
  1203     result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
  1204                                str1_start, str2_start, str1_len);
  1205     break;
  1206   default:
  1207     ShouldNotReachHere();
  1208     return NULL;
  1211   // All these intrinsics have checks.
  1212   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1214   return _gvn.transform(result);
  1217 // Helper method for String intrinsic functions. This version is called
  1218 // with str1 and str2 pointing to char[] nodes, with cnt1 and cnt2 pointing
  1219 // to Int nodes containing the lenghts of str1 and str2.
  1220 //
  1221 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2) {
  1222   Node* result = NULL;
  1223   switch (opcode) {
  1224   case Op_StrIndexOf:
  1225     result = new (C) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
  1226                                  str1_start, cnt1, str2_start, cnt2);
  1227     break;
  1228   case Op_StrComp:
  1229     result = new (C) StrCompNode(control(), memory(TypeAryPtr::CHARS),
  1230                                  str1_start, cnt1, str2_start, cnt2);
  1231     break;
  1232   case Op_StrEquals:
  1233     result = new (C) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
  1234                                  str1_start, str2_start, cnt1);
  1235     break;
  1236   default:
  1237     ShouldNotReachHere();
  1238     return NULL;
  1241   // All these intrinsics have checks.
  1242   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1244   return _gvn.transform(result);
  1247 //------------------------------inline_string_compareTo------------------------
  1248 // public int java.lang.String.compareTo(String anotherString);
  1249 bool LibraryCallKit::inline_string_compareTo() {
  1250   Node* receiver = null_check(argument(0));
  1251   Node* arg      = null_check(argument(1));
  1252   if (stopped()) {
  1253     return true;
  1255   set_result(make_string_method_node(Op_StrComp, receiver, arg));
  1256   return true;
  1259 //------------------------------inline_string_equals------------------------
  1260 bool LibraryCallKit::inline_string_equals() {
  1261   Node* receiver = null_check_receiver();
  1262   // NOTE: Do not null check argument for String.equals() because spec
  1263   // allows to specify NULL as argument.
  1264   Node* argument = this->argument(1);
  1265   if (stopped()) {
  1266     return true;
  1269   // paths (plus control) merge
  1270   RegionNode* region = new (C) RegionNode(5);
  1271   Node* phi = new (C) PhiNode(region, TypeInt::BOOL);
  1273   // does source == target string?
  1274   Node* cmp = _gvn.transform(new (C) CmpPNode(receiver, argument));
  1275   Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));
  1277   Node* if_eq = generate_slow_guard(bol, NULL);
  1278   if (if_eq != NULL) {
  1279     // receiver == argument
  1280     phi->init_req(2, intcon(1));
  1281     region->init_req(2, if_eq);
  1284   // get String klass for instanceOf
  1285   ciInstanceKlass* klass = env()->String_klass();
  1287   if (!stopped()) {
  1288     Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
  1289     Node* cmp  = _gvn.transform(new (C) CmpINode(inst, intcon(1)));
  1290     Node* bol  = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));
  1292     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
  1293     //instanceOf == true, fallthrough
  1295     if (inst_false != NULL) {
  1296       phi->init_req(3, intcon(0));
  1297       region->init_req(3, inst_false);
  1301   if (!stopped()) {
  1302     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
  1304     // Properly cast the argument to String
  1305     argument = _gvn.transform(new (C) CheckCastPPNode(control(), argument, string_type));
  1306     // This path is taken only when argument's type is String:NotNull.
  1307     argument = cast_not_null(argument, false);
  1309     Node* no_ctrl = NULL;
  1311     // Get start addr of receiver
  1312     Node* receiver_val    = load_String_value(no_ctrl, receiver);
  1313     Node* receiver_offset = load_String_offset(no_ctrl, receiver);
  1314     Node* receiver_start = array_element_address(receiver_val, receiver_offset, T_CHAR);
  1316     // Get length of receiver
  1317     Node* receiver_cnt  = load_String_length(no_ctrl, receiver);
  1319     // Get start addr of argument
  1320     Node* argument_val    = load_String_value(no_ctrl, argument);
  1321     Node* argument_offset = load_String_offset(no_ctrl, argument);
  1322     Node* argument_start = array_element_address(argument_val, argument_offset, T_CHAR);
  1324     // Get length of argument
  1325     Node* argument_cnt  = load_String_length(no_ctrl, argument);
  1327     // Check for receiver count != argument count
  1328     Node* cmp = _gvn.transform(new(C) CmpINode(receiver_cnt, argument_cnt));
  1329     Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::ne));
  1330     Node* if_ne = generate_slow_guard(bol, NULL);
  1331     if (if_ne != NULL) {
  1332       phi->init_req(4, intcon(0));
  1333       region->init_req(4, if_ne);
  1336     // Check for count == 0 is done by assembler code for StrEquals.
  1338     if (!stopped()) {
  1339       Node* equals = make_string_method_node(Op_StrEquals, receiver_start, receiver_cnt, argument_start, argument_cnt);
  1340       phi->init_req(1, equals);
  1341       region->init_req(1, control());
  1345   // post merge
  1346   set_control(_gvn.transform(region));
  1347   record_for_igvn(region);
  1349   set_result(_gvn.transform(phi));
  1350   return true;
  1353 //------------------------------inline_array_equals----------------------------
  1354 bool LibraryCallKit::inline_array_equals() {
  1355   Node* arg1 = argument(0);
  1356   Node* arg2 = argument(1);
  1357   set_result(_gvn.transform(new (C) AryEqNode(control(), memory(TypeAryPtr::CHARS), arg1, arg2)));
  1358   return true;
  1361 // Java version of String.indexOf(constant string)
  1362 // class StringDecl {
  1363 //   StringDecl(char[] ca) {
  1364 //     offset = 0;
  1365 //     count = ca.length;
  1366 //     value = ca;
  1367 //   }
  1368 //   int offset;
  1369 //   int count;
  1370 //   char[] value;
  1371 // }
  1372 //
  1373 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
  1374 //                             int targetOffset, int cache_i, int md2) {
  1375 //   int cache = cache_i;
  1376 //   int sourceOffset = string_object.offset;
  1377 //   int sourceCount = string_object.count;
  1378 //   int targetCount = target_object.length;
  1379 //
  1380 //   int targetCountLess1 = targetCount - 1;
  1381 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
  1382 //
  1383 //   char[] source = string_object.value;
  1384 //   char[] target = target_object;
  1385 //   int lastChar = target[targetCountLess1];
  1386 //
  1387 //  outer_loop:
  1388 //   for (int i = sourceOffset; i < sourceEnd; ) {
  1389 //     int src = source[i + targetCountLess1];
  1390 //     if (src == lastChar) {
  1391 //       // With random strings and a 4-character alphabet,
  1392 //       // reverse matching at this point sets up 0.8% fewer
  1393 //       // frames, but (paradoxically) makes 0.3% more probes.
  1394 //       // Since those probes are nearer the lastChar probe,
  1395 //       // there is may be a net D$ win with reverse matching.
  1396 //       // But, reversing loop inhibits unroll of inner loop
  1397 //       // for unknown reason.  So, does running outer loop from
  1398 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
  1399 //       for (int j = 0; j < targetCountLess1; j++) {
  1400 //         if (target[targetOffset + j] != source[i+j]) {
  1401 //           if ((cache & (1 << source[i+j])) == 0) {
  1402 //             if (md2 < j+1) {
  1403 //               i += j+1;
  1404 //               continue outer_loop;
  1405 //             }
  1406 //           }
  1407 //           i += md2;
  1408 //           continue outer_loop;
  1409 //         }
  1410 //       }
  1411 //       return i - sourceOffset;
  1412 //     }
  1413 //     if ((cache & (1 << src)) == 0) {
  1414 //       i += targetCountLess1;
  1415 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
  1416 //     i++;
  1417 //   }
  1418 //   return -1;
  1419 // }
  1421 //------------------------------string_indexOf------------------------
  1422 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
  1423                                      jint cache_i, jint md2_i) {
  1425   Node* no_ctrl  = NULL;
  1426   float likely   = PROB_LIKELY(0.9);
  1427   float unlikely = PROB_UNLIKELY(0.9);
  1429   const int nargs = 0; // no arguments to push back for uncommon trap in predicate
  1431   Node* source        = load_String_value(no_ctrl, string_object);
  1432   Node* sourceOffset  = load_String_offset(no_ctrl, string_object);
  1433   Node* sourceCount   = load_String_length(no_ctrl, string_object);
  1435   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)));
  1436   jint target_length = target_array->length();
  1437   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
  1438   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
  1440   // String.value field is known to be @Stable.
  1441   if (UseImplicitStableValues) {
  1442     target = cast_array_to_stable(target, target_type);
  1445   IdealKit kit(this, false, true);
  1446 #define __ kit.
  1447   Node* zero             = __ ConI(0);
  1448   Node* one              = __ ConI(1);
  1449   Node* cache            = __ ConI(cache_i);
  1450   Node* md2              = __ ConI(md2_i);
  1451   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
  1452   Node* targetCount      = __ ConI(target_length);
  1453   Node* targetCountLess1 = __ ConI(target_length - 1);
  1454   Node* targetOffset     = __ ConI(targetOffset_i);
  1455   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
  1457   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
  1458   Node* outer_loop = __ make_label(2 /* goto */);
  1459   Node* return_    = __ make_label(1);
  1461   __ set(rtn,__ ConI(-1));
  1462   __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
  1463        Node* i2  = __ AddI(__ value(i), targetCountLess1);
  1464        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
  1465        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
  1466        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
  1467          __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
  1468               Node* tpj = __ AddI(targetOffset, __ value(j));
  1469               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
  1470               Node* ipj  = __ AddI(__ value(i), __ value(j));
  1471               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
  1472               __ if_then(targ, BoolTest::ne, src2); {
  1473                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
  1474                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
  1475                     __ increment(i, __ AddI(__ value(j), one));
  1476                     __ goto_(outer_loop);
  1477                   } __ end_if(); __ dead(j);
  1478                 }__ end_if(); __ dead(j);
  1479                 __ increment(i, md2);
  1480                 __ goto_(outer_loop);
  1481               }__ end_if();
  1482               __ increment(j, one);
  1483          }__ end_loop(); __ dead(j);
  1484          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
  1485          __ goto_(return_);
  1486        }__ end_if();
  1487        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
  1488          __ increment(i, targetCountLess1);
  1489        }__ end_if();
  1490        __ increment(i, one);
  1491        __ bind(outer_loop);
  1492   }__ end_loop(); __ dead(i);
  1493   __ bind(return_);
  1495   // Final sync IdealKit and GraphKit.
  1496   final_sync(kit);
  1497   Node* result = __ value(rtn);
  1498 #undef __
  1499   C->set_has_loops(true);
  1500   return result;
  1503 //------------------------------inline_string_indexOf------------------------
  1504 bool LibraryCallKit::inline_string_indexOf() {
  1505   Node* receiver = argument(0);
  1506   Node* arg      = argument(1);
  1508   Node* result;
  1509   // Disable the use of pcmpestri until it can be guaranteed that
  1510   // the load doesn't cross into the uncommited space.
  1511   if (Matcher::has_match_rule(Op_StrIndexOf) &&
  1512       UseSSE42Intrinsics) {
  1513     // Generate SSE4.2 version of indexOf
  1514     // We currently only have match rules that use SSE4.2
  1516     receiver = null_check(receiver);
  1517     arg      = null_check(arg);
  1518     if (stopped()) {
  1519       return true;
  1522     ciInstanceKlass* str_klass = env()->String_klass();
  1523     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);
  1525     // Make the merge point
  1526     RegionNode* result_rgn = new (C) RegionNode(4);
  1527     Node*       result_phi = new (C) PhiNode(result_rgn, TypeInt::INT);
  1528     Node* no_ctrl  = NULL;
  1530     // Get start addr of source string
  1531     Node* source = load_String_value(no_ctrl, receiver);
  1532     Node* source_offset = load_String_offset(no_ctrl, receiver);
  1533     Node* source_start = array_element_address(source, source_offset, T_CHAR);
  1535     // Get length of source string
  1536     Node* source_cnt  = load_String_length(no_ctrl, receiver);
  1538     // Get start addr of substring
  1539     Node* substr = load_String_value(no_ctrl, arg);
  1540     Node* substr_offset = load_String_offset(no_ctrl, arg);
  1541     Node* substr_start = array_element_address(substr, substr_offset, T_CHAR);
  1543     // Get length of source string
  1544     Node* substr_cnt  = load_String_length(no_ctrl, arg);
  1546     // Check for substr count > string count
  1547     Node* cmp = _gvn.transform(new(C) CmpINode(substr_cnt, source_cnt));
  1548     Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::gt));
  1549     Node* if_gt = generate_slow_guard(bol, NULL);
  1550     if (if_gt != NULL) {
  1551       result_phi->init_req(2, intcon(-1));
  1552       result_rgn->init_req(2, if_gt);
  1555     if (!stopped()) {
  1556       // Check for substr count == 0
  1557       cmp = _gvn.transform(new(C) CmpINode(substr_cnt, intcon(0)));
  1558       bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));
  1559       Node* if_zero = generate_slow_guard(bol, NULL);
  1560       if (if_zero != NULL) {
  1561         result_phi->init_req(3, intcon(0));
  1562         result_rgn->init_req(3, if_zero);
  1566     if (!stopped()) {
  1567       result = make_string_method_node(Op_StrIndexOf, source_start, source_cnt, substr_start, substr_cnt);
  1568       result_phi->init_req(1, result);
  1569       result_rgn->init_req(1, control());
  1571     set_control(_gvn.transform(result_rgn));
  1572     record_for_igvn(result_rgn);
  1573     result = _gvn.transform(result_phi);
  1575   } else { // Use LibraryCallKit::string_indexOf
  1576     // don't intrinsify if argument isn't a constant string.
  1577     if (!arg->is_Con()) {
  1578      return false;
  1580     const TypeOopPtr* str_type = _gvn.type(arg)->isa_oopptr();
  1581     if (str_type == NULL) {
  1582       return false;
  1584     ciInstanceKlass* klass = env()->String_klass();
  1585     ciObject* str_const = str_type->const_oop();
  1586     if (str_const == NULL || str_const->klass() != klass) {
  1587       return false;
  1589     ciInstance* str = str_const->as_instance();
  1590     assert(str != NULL, "must be instance");
  1592     ciObject* v = str->field_value_by_offset(java_lang_String::value_offset_in_bytes()).as_object();
  1593     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
  1595     int o;
  1596     int c;
  1597     if (java_lang_String::has_offset_field()) {
  1598       o = str->field_value_by_offset(java_lang_String::offset_offset_in_bytes()).as_int();
  1599       c = str->field_value_by_offset(java_lang_String::count_offset_in_bytes()).as_int();
  1600     } else {
  1601       o = 0;
  1602       c = pat->length();
  1605     // constant strings have no offset and count == length which
  1606     // simplifies the resulting code somewhat so lets optimize for that.
  1607     if (o != 0 || c != pat->length()) {
  1608      return false;
  1611     receiver = null_check(receiver, T_OBJECT);
  1612     // NOTE: No null check on the argument is needed since it's a constant String oop.
  1613     if (stopped()) {
  1614       return true;
  1617     // The null string as a pattern always returns 0 (match at beginning of string)
  1618     if (c == 0) {
  1619       set_result(intcon(0));
  1620       return true;
  1623     // Generate default indexOf
  1624     jchar lastChar = pat->char_at(o + (c - 1));
  1625     int cache = 0;
  1626     int i;
  1627     for (i = 0; i < c - 1; i++) {
  1628       assert(i < pat->length(), "out of range");
  1629       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
  1632     int md2 = c;
  1633     for (i = 0; i < c - 1; i++) {
  1634       assert(i < pat->length(), "out of range");
  1635       if (pat->char_at(o + i) == lastChar) {
  1636         md2 = (c - 1) - i;
  1640     result = string_indexOf(receiver, pat, o, cache, md2);
  1642   set_result(result);
  1643   return true;
  1646 //--------------------------round_double_node--------------------------------
  1647 // Round a double node if necessary.
  1648 Node* LibraryCallKit::round_double_node(Node* n) {
  1649   if (Matcher::strict_fp_requires_explicit_rounding && UseSSE <= 1)
  1650     n = _gvn.transform(new (C) RoundDoubleNode(0, n));
  1651   return n;
  1654 //------------------------------inline_math-----------------------------------
  1655 // public static double Math.abs(double)
  1656 // public static double Math.sqrt(double)
  1657 // public static double Math.log(double)
  1658 // public static double Math.log10(double)
  1659 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
  1660   Node* arg = round_double_node(argument(0));
  1661   Node* n = NULL;
  1662   switch (id) {
  1663   case vmIntrinsics::_dabs:   n = new (C) AbsDNode(                arg);  break;
  1664   case vmIntrinsics::_dsqrt:  n = new (C) SqrtDNode(C, control(),  arg);  break;
  1665   case vmIntrinsics::_dlog:   n = new (C) LogDNode(C, control(),   arg);  break;
  1666   case vmIntrinsics::_dlog10: n = new (C) Log10DNode(C, control(), arg);  break;
  1667   default:  fatal_unexpected_iid(id);  break;
  1669   set_result(_gvn.transform(n));
  1670   return true;
  1673 //------------------------------inline_trig----------------------------------
  1674 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
  1675 // argument reduction which will turn into a fast/slow diamond.
  1676 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
  1677   Node* arg = round_double_node(argument(0));
  1678   Node* n = NULL;
  1680   switch (id) {
  1681   case vmIntrinsics::_dsin:  n = new (C) SinDNode(C, control(), arg);  break;
  1682   case vmIntrinsics::_dcos:  n = new (C) CosDNode(C, control(), arg);  break;
  1683   case vmIntrinsics::_dtan:  n = new (C) TanDNode(C, control(), arg);  break;
  1684   default:  fatal_unexpected_iid(id);  break;
  1686   n = _gvn.transform(n);
  1688   // Rounding required?  Check for argument reduction!
  1689   if (Matcher::strict_fp_requires_explicit_rounding) {
  1690     static const double     pi_4 =  0.7853981633974483;
  1691     static const double neg_pi_4 = -0.7853981633974483;
  1692     // pi/2 in 80-bit extended precision
  1693     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
  1694     // -pi/2 in 80-bit extended precision
  1695     // 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};
  1696     // Cutoff value for using this argument reduction technique
  1697     //static const double    pi_2_minus_epsilon =  1.564660403643354;
  1698     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
  1700     // Pseudocode for sin:
  1701     // if (x <= Math.PI / 4.0) {
  1702     //   if (x >= -Math.PI / 4.0) return  fsin(x);
  1703     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
  1704     // } else {
  1705     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
  1706     // }
  1707     // return StrictMath.sin(x);
  1709     // Pseudocode for cos:
  1710     // if (x <= Math.PI / 4.0) {
  1711     //   if (x >= -Math.PI / 4.0) return  fcos(x);
  1712     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
  1713     // } else {
  1714     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
  1715     // }
  1716     // return StrictMath.cos(x);
  1718     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
  1719     // requires a special machine instruction to load it.  Instead we'll try
  1720     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
  1721     // probably do the math inside the SIN encoding.
  1723     // Make the merge point
  1724     RegionNode* r = new (C) RegionNode(3);
  1725     Node* phi = new (C) PhiNode(r, Type::DOUBLE);
  1727     // Flatten arg so we need only 1 test
  1728     Node *abs = _gvn.transform(new (C) AbsDNode(arg));
  1729     // Node for PI/4 constant
  1730     Node *pi4 = makecon(TypeD::make(pi_4));
  1731     // Check PI/4 : abs(arg)
  1732     Node *cmp = _gvn.transform(new (C) CmpDNode(pi4,abs));
  1733     // Check: If PI/4 < abs(arg) then go slow
  1734     Node *bol = _gvn.transform(new (C) BoolNode( cmp, BoolTest::lt ));
  1735     // Branch either way
  1736     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  1737     set_control(opt_iff(r,iff));
  1739     // Set fast path result
  1740     phi->init_req(2, n);
  1742     // Slow path - non-blocking leaf call
  1743     Node* call = NULL;
  1744     switch (id) {
  1745     case vmIntrinsics::_dsin:
  1746       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1747                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
  1748                                "Sin", NULL, arg, top());
  1749       break;
  1750     case vmIntrinsics::_dcos:
  1751       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1752                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
  1753                                "Cos", NULL, arg, top());
  1754       break;
  1755     case vmIntrinsics::_dtan:
  1756       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1757                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
  1758                                "Tan", NULL, arg, top());
  1759       break;
  1761     assert(control()->in(0) == call, "");
  1762     Node* slow_result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  1763     r->init_req(1, control());
  1764     phi->init_req(1, slow_result);
  1766     // Post-merge
  1767     set_control(_gvn.transform(r));
  1768     record_for_igvn(r);
  1769     n = _gvn.transform(phi);
  1771     C->set_has_split_ifs(true); // Has chance for split-if optimization
  1773   set_result(n);
  1774   return true;
  1777 Node* LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFunc* call_type, address funcAddr, const char* funcName) {
  1778   //-------------------
  1779   //result=(result.isNaN())? funcAddr():result;
  1780   // Check: If isNaN() by checking result!=result? then either trap
  1781   // or go to runtime
  1782   Node* cmpisnan = _gvn.transform(new (C) CmpDNode(result, result));
  1783   // Build the boolean node
  1784   Node* bolisnum = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::eq));
  1786   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
  1787     { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
  1788       // The pow or exp intrinsic returned a NaN, which requires a call
  1789       // to the runtime.  Recompile with the runtime call.
  1790       uncommon_trap(Deoptimization::Reason_intrinsic,
  1791                     Deoptimization::Action_make_not_entrant);
  1793     return result;
  1794   } else {
  1795     // If this inlining ever returned NaN in the past, we compile a call
  1796     // to the runtime to properly handle corner cases
  1798     IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  1799     Node* if_slow = _gvn.transform(new (C) IfFalseNode(iff));
  1800     Node* if_fast = _gvn.transform(new (C) IfTrueNode(iff));
  1802     if (!if_slow->is_top()) {
  1803       RegionNode* result_region = new (C) RegionNode(3);
  1804       PhiNode*    result_val = new (C) PhiNode(result_region, Type::DOUBLE);
  1806       result_region->init_req(1, if_fast);
  1807       result_val->init_req(1, result);
  1809       set_control(if_slow);
  1811       const TypePtr* no_memory_effects = NULL;
  1812       Node* rt = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
  1813                                    no_memory_effects,
  1814                                    x, top(), y, y ? top() : NULL);
  1815       Node* value = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+0));
  1816 #ifdef ASSERT
  1817       Node* value_top = _gvn.transform(new (C) ProjNode(rt, TypeFunc::Parms+1));
  1818       assert(value_top == top(), "second value must be top");
  1819 #endif
  1821       result_region->init_req(2, control());
  1822       result_val->init_req(2, value);
  1823       set_control(_gvn.transform(result_region));
  1824       return _gvn.transform(result_val);
  1825     } else {
  1826       return result;
  1831 //------------------------------inline_exp-------------------------------------
  1832 // Inline exp instructions, if possible.  The Intel hardware only misses
  1833 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
  1834 bool LibraryCallKit::inline_exp() {
  1835   Node* arg = round_double_node(argument(0));
  1836   Node* n   = _gvn.transform(new (C) ExpDNode(C, control(), arg));
  1838   n = finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
  1839   set_result(n);
  1841   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1842   return true;
  1845 //------------------------------inline_pow-------------------------------------
  1846 // Inline power instructions, if possible.
  1847 bool LibraryCallKit::inline_pow() {
  1848   // Pseudocode for pow
  1849   // if (y == 2) {
  1850   //   return x * x;
  1851   // } else {
  1852   //   if (x <= 0.0) {
  1853   //     long longy = (long)y;
  1854   //     if ((double)longy == y) { // if y is long
  1855   //       if (y + 1 == y) longy = 0; // huge number: even
  1856   //       result = ((1&longy) == 0)?-DPow(abs(x), y):DPow(abs(x), y);
  1857   //     } else {
  1858   //       result = NaN;
  1859   //     }
  1860   //   } else {
  1861   //     result = DPow(x,y);
  1862   //   }
  1863   //   if (result != result)?  {
  1864   //     result = uncommon_trap() or runtime_call();
  1865   //   }
  1866   //   return result;
  1867   // }
  1869   Node* x = round_double_node(argument(0));
  1870   Node* y = round_double_node(argument(2));
  1872   Node* result = NULL;
  1874   Node*   const_two_node = makecon(TypeD::make(2.0));
  1875   Node*   cmp_node       = _gvn.transform(new (C) CmpDNode(y, const_two_node));
  1876   Node*   bool_node      = _gvn.transform(new (C) BoolNode(cmp_node, BoolTest::eq));
  1877   IfNode* if_node        = create_and_xform_if(control(), bool_node, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1878   Node*   if_true        = _gvn.transform(new (C) IfTrueNode(if_node));
  1879   Node*   if_false       = _gvn.transform(new (C) IfFalseNode(if_node));
  1881   RegionNode* region_node = new (C) RegionNode(3);
  1882   region_node->init_req(1, if_true);
  1884   Node* phi_node = new (C) PhiNode(region_node, Type::DOUBLE);
  1885   // special case for x^y where y == 2, we can convert it to x * x
  1886   phi_node->init_req(1, _gvn.transform(new (C) MulDNode(x, x)));
  1888   // set control to if_false since we will now process the false branch
  1889   set_control(if_false);
  1891   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
  1892     // Short form: skip the fancy tests and just check for NaN result.
  1893     result = _gvn.transform(new (C) PowDNode(C, control(), x, y));
  1894   } else {
  1895     // If this inlining ever returned NaN in the past, include all
  1896     // checks + call to the runtime.
  1898     // Set the merge point for If node with condition of (x <= 0.0)
  1899     // There are four possible paths to region node and phi node
  1900     RegionNode *r = new (C) RegionNode(4);
  1901     Node *phi = new (C) PhiNode(r, Type::DOUBLE);
  1903     // Build the first if node: if (x <= 0.0)
  1904     // Node for 0 constant
  1905     Node *zeronode = makecon(TypeD::ZERO);
  1906     // Check x:0
  1907     Node *cmp = _gvn.transform(new (C) CmpDNode(x, zeronode));
  1908     // Check: If (x<=0) then go complex path
  1909     Node *bol1 = _gvn.transform(new (C) BoolNode( cmp, BoolTest::le ));
  1910     // Branch either way
  1911     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1912     // Fast path taken; set region slot 3
  1913     Node *fast_taken = _gvn.transform(new (C) IfFalseNode(if1));
  1914     r->init_req(3,fast_taken); // Capture fast-control
  1916     // Fast path not-taken, i.e. slow path
  1917     Node *complex_path = _gvn.transform(new (C) IfTrueNode(if1));
  1919     // Set fast path result
  1920     Node *fast_result = _gvn.transform(new (C) PowDNode(C, control(), x, y));
  1921     phi->init_req(3, fast_result);
  1923     // Complex path
  1924     // Build the second if node (if y is long)
  1925     // Node for (long)y
  1926     Node *longy = _gvn.transform(new (C) ConvD2LNode(y));
  1927     // Node for (double)((long) y)
  1928     Node *doublelongy= _gvn.transform(new (C) ConvL2DNode(longy));
  1929     // Check (double)((long) y) : y
  1930     Node *cmplongy= _gvn.transform(new (C) CmpDNode(doublelongy, y));
  1931     // Check if (y isn't long) then go to slow path
  1933     Node *bol2 = _gvn.transform(new (C) BoolNode( cmplongy, BoolTest::ne ));
  1934     // Branch either way
  1935     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1936     Node* ylong_path = _gvn.transform(new (C) IfFalseNode(if2));
  1938     Node *slow_path = _gvn.transform(new (C) IfTrueNode(if2));
  1940     // Calculate DPow(abs(x), y)*(1 & (long)y)
  1941     // Node for constant 1
  1942     Node *conone = longcon(1);
  1943     // 1& (long)y
  1944     Node *signnode= _gvn.transform(new (C) AndLNode(conone, longy));
  1946     // A huge number is always even. Detect a huge number by checking
  1947     // if y + 1 == y and set integer to be tested for parity to 0.
  1948     // Required for corner case:
  1949     // (long)9.223372036854776E18 = max_jlong
  1950     // (double)(long)9.223372036854776E18 = 9.223372036854776E18
  1951     // max_jlong is odd but 9.223372036854776E18 is even
  1952     Node* yplus1 = _gvn.transform(new (C) AddDNode(y, makecon(TypeD::make(1))));
  1953     Node *cmpyplus1= _gvn.transform(new (C) CmpDNode(yplus1, y));
  1954     Node *bolyplus1 = _gvn.transform(new (C) BoolNode( cmpyplus1, BoolTest::eq ));
  1955     Node* correctedsign = NULL;
  1956     if (ConditionalMoveLimit != 0) {
  1957       correctedsign = _gvn.transform( CMoveNode::make(C, NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG));
  1958     } else {
  1959       IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN);
  1960       RegionNode *r = new (C) RegionNode(3);
  1961       Node *phi = new (C) PhiNode(r, TypeLong::LONG);
  1962       r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyplus1)));
  1963       r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyplus1)));
  1964       phi->init_req(1, signnode);
  1965       phi->init_req(2, longcon(0));
  1966       correctedsign = _gvn.transform(phi);
  1967       ylong_path = _gvn.transform(r);
  1968       record_for_igvn(r);
  1971     // zero node
  1972     Node *conzero = longcon(0);
  1973     // Check (1&(long)y)==0?
  1974     Node *cmpeq1 = _gvn.transform(new (C) CmpLNode(correctedsign, conzero));
  1975     // Check if (1&(long)y)!=0?, if so the result is negative
  1976     Node *bol3 = _gvn.transform(new (C) BoolNode( cmpeq1, BoolTest::ne ));
  1977     // abs(x)
  1978     Node *absx=_gvn.transform(new (C) AbsDNode(x));
  1979     // abs(x)^y
  1980     Node *absxpowy = _gvn.transform(new (C) PowDNode(C, control(), absx, y));
  1981     // -abs(x)^y
  1982     Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy));
  1983     // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
  1984     Node *signresult = NULL;
  1985     if (ConditionalMoveLimit != 0) {
  1986       signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
  1987     } else {
  1988       IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN);
  1989       RegionNode *r = new (C) RegionNode(3);
  1990       Node *phi = new (C) PhiNode(r, Type::DOUBLE);
  1991       r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyeven)));
  1992       r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyeven)));
  1993       phi->init_req(1, absxpowy);
  1994       phi->init_req(2, negabsxpowy);
  1995       signresult = _gvn.transform(phi);
  1996       ylong_path = _gvn.transform(r);
  1997       record_for_igvn(r);
  1999     // Set complex path fast result
  2000     r->init_req(2, ylong_path);
  2001     phi->init_req(2, signresult);
  2003     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  2004     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
  2005     r->init_req(1,slow_path);
  2006     phi->init_req(1,slow_result);
  2008     // Post merge
  2009     set_control(_gvn.transform(r));
  2010     record_for_igvn(r);
  2011     result = _gvn.transform(phi);
  2014   result = finish_pow_exp(result, x, y, OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
  2016   // control from finish_pow_exp is now input to the region node
  2017   region_node->set_req(2, control());
  2018   // the result from finish_pow_exp is now input to the phi node
  2019   phi_node->init_req(2, result);
  2020   set_control(_gvn.transform(region_node));
  2021   record_for_igvn(region_node);
  2022   set_result(_gvn.transform(phi_node));
  2024   C->set_has_split_ifs(true); // Has chance for split-if optimization
  2025   return true;
  2028 //------------------------------runtime_math-----------------------------
  2029 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
  2030   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
  2031          "must be (DD)D or (D)D type");
  2033   // Inputs
  2034   Node* a = round_double_node(argument(0));
  2035   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
  2037   const TypePtr* no_memory_effects = NULL;
  2038   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
  2039                                  no_memory_effects,
  2040                                  a, top(), b, b ? top() : NULL);
  2041   Node* value = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+0));
  2042 #ifdef ASSERT
  2043   Node* value_top = _gvn.transform(new (C) ProjNode(trig, TypeFunc::Parms+1));
  2044   assert(value_top == top(), "second value must be top");
  2045 #endif
  2047   set_result(value);
  2048   return true;
  2051 //------------------------------inline_math_native-----------------------------
  2052 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
  2053 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
  2054   switch (id) {
  2055     // These intrinsics are not properly supported on all hardware
  2056   case vmIntrinsics::_dcos:   return Matcher::has_match_rule(Op_CosD)   ? inline_trig(id) :
  2057     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos),   "COS");
  2058   case vmIntrinsics::_dsin:   return Matcher::has_match_rule(Op_SinD)   ? inline_trig(id) :
  2059     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin),   "SIN");
  2060   case vmIntrinsics::_dtan:   return Matcher::has_match_rule(Op_TanD)   ? inline_trig(id) :
  2061     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan),   "TAN");
  2063   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD)   ? inline_math(id) :
  2064     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog),   "LOG");
  2065   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_math(id) :
  2066     runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
  2068     // These intrinsics are supported on all hardware
  2069   case vmIntrinsics::_dsqrt:  return Matcher::match_rule_supported(Op_SqrtD) ? inline_math(id) : false;
  2070   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_math(id) : false;
  2072   case vmIntrinsics::_dexp:   return Matcher::has_match_rule(Op_ExpD)   ? inline_exp()    :
  2073     runtime_math(OptoRuntime::Math_D_D_Type(),  FN_PTR(SharedRuntime::dexp),  "EXP");
  2074   case vmIntrinsics::_dpow:   return Matcher::has_match_rule(Op_PowD)   ? inline_pow()    :
  2075     runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow),  "POW");
  2076 #undef FN_PTR
  2078    // These intrinsics are not yet correctly implemented
  2079   case vmIntrinsics::_datan2:
  2080     return false;
  2082   default:
  2083     fatal_unexpected_iid(id);
  2084     return false;
  2088 static bool is_simple_name(Node* n) {
  2089   return (n->req() == 1         // constant
  2090           || (n->is_Type() && n->as_Type()->type()->singleton())
  2091           || n->is_Proj()       // parameter or return value
  2092           || n->is_Phi()        // local of some sort
  2093           );
  2096 //----------------------------inline_min_max-----------------------------------
  2097 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
  2098   set_result(generate_min_max(id, argument(0), argument(1)));
  2099   return true;
  2102 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
  2103   Node* bol = _gvn.transform( new (C) BoolNode(test, BoolTest::overflow) );
  2104   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
  2105   Node* fast_path = _gvn.transform( new (C) IfFalseNode(check));
  2106   Node* slow_path = _gvn.transform( new (C) IfTrueNode(check) );
  2109     PreserveJVMState pjvms(this);
  2110     PreserveReexecuteState preexecs(this);
  2111     jvms()->set_should_reexecute(true);
  2113     set_control(slow_path);
  2114     set_i_o(i_o());
  2116     uncommon_trap(Deoptimization::Reason_intrinsic,
  2117                   Deoptimization::Action_none);
  2120   set_control(fast_path);
  2121   set_result(math);
  2124 template <typename OverflowOp>
  2125 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
  2126   typedef typename OverflowOp::MathOp MathOp;
  2128   MathOp* mathOp = new(C) MathOp(arg1, arg2);
  2129   Node* operation = _gvn.transform( mathOp );
  2130   Node* ofcheck = _gvn.transform( new(C) OverflowOp(arg1, arg2) );
  2131   inline_math_mathExact(operation, ofcheck);
  2132   return true;
  2135 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
  2136   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
  2139 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
  2140   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
  2143 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
  2144   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
  2147 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
  2148   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
  2151 bool LibraryCallKit::inline_math_negateExactI() {
  2152   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
  2155 bool LibraryCallKit::inline_math_negateExactL() {
  2156   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
  2159 bool LibraryCallKit::inline_math_multiplyExactI() {
  2160   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
  2163 bool LibraryCallKit::inline_math_multiplyExactL() {
  2164   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
  2167 Node*
  2168 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
  2169   // These are the candidate return value:
  2170   Node* xvalue = x0;
  2171   Node* yvalue = y0;
  2173   if (xvalue == yvalue) {
  2174     return xvalue;
  2177   bool want_max = (id == vmIntrinsics::_max);
  2179   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
  2180   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
  2181   if (txvalue == NULL || tyvalue == NULL)  return top();
  2182   // This is not really necessary, but it is consistent with a
  2183   // hypothetical MaxINode::Value method:
  2184   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
  2186   // %%% This folding logic should (ideally) be in a different place.
  2187   // Some should be inside IfNode, and there to be a more reliable
  2188   // transformation of ?: style patterns into cmoves.  We also want
  2189   // more powerful optimizations around cmove and min/max.
  2191   // Try to find a dominating comparison of these guys.
  2192   // It can simplify the index computation for Arrays.copyOf
  2193   // and similar uses of System.arraycopy.
  2194   // First, compute the normalized version of CmpI(x, y).
  2195   int   cmp_op = Op_CmpI;
  2196   Node* xkey = xvalue;
  2197   Node* ykey = yvalue;
  2198   Node* ideal_cmpxy = _gvn.transform(new(C) CmpINode(xkey, ykey));
  2199   if (ideal_cmpxy->is_Cmp()) {
  2200     // E.g., if we have CmpI(length - offset, count),
  2201     // it might idealize to CmpI(length, count + offset)
  2202     cmp_op = ideal_cmpxy->Opcode();
  2203     xkey = ideal_cmpxy->in(1);
  2204     ykey = ideal_cmpxy->in(2);
  2207   // Start by locating any relevant comparisons.
  2208   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
  2209   Node* cmpxy = NULL;
  2210   Node* cmpyx = NULL;
  2211   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
  2212     Node* cmp = start_from->fast_out(k);
  2213     if (cmp->outcnt() > 0 &&            // must have prior uses
  2214         cmp->in(0) == NULL &&           // must be context-independent
  2215         cmp->Opcode() == cmp_op) {      // right kind of compare
  2216       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
  2217       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
  2221   const int NCMPS = 2;
  2222   Node* cmps[NCMPS] = { cmpxy, cmpyx };
  2223   int cmpn;
  2224   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  2225     if (cmps[cmpn] != NULL)  break;     // find a result
  2227   if (cmpn < NCMPS) {
  2228     // Look for a dominating test that tells us the min and max.
  2229     int depth = 0;                // Limit search depth for speed
  2230     Node* dom = control();
  2231     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
  2232       if (++depth >= 100)  break;
  2233       Node* ifproj = dom;
  2234       if (!ifproj->is_Proj())  continue;
  2235       Node* iff = ifproj->in(0);
  2236       if (!iff->is_If())  continue;
  2237       Node* bol = iff->in(1);
  2238       if (!bol->is_Bool())  continue;
  2239       Node* cmp = bol->in(1);
  2240       if (cmp == NULL)  continue;
  2241       for (cmpn = 0; cmpn < NCMPS; cmpn++)
  2242         if (cmps[cmpn] == cmp)  break;
  2243       if (cmpn == NCMPS)  continue;
  2244       BoolTest::mask btest = bol->as_Bool()->_test._test;
  2245       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
  2246       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
  2247       // At this point, we know that 'x btest y' is true.
  2248       switch (btest) {
  2249       case BoolTest::eq:
  2250         // They are proven equal, so we can collapse the min/max.
  2251         // Either value is the answer.  Choose the simpler.
  2252         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
  2253           return yvalue;
  2254         return xvalue;
  2255       case BoolTest::lt:          // x < y
  2256       case BoolTest::le:          // x <= y
  2257         return (want_max ? yvalue : xvalue);
  2258       case BoolTest::gt:          // x > y
  2259       case BoolTest::ge:          // x >= y
  2260         return (want_max ? xvalue : yvalue);
  2265   // We failed to find a dominating test.
  2266   // Let's pick a test that might GVN with prior tests.
  2267   Node*          best_bol   = NULL;
  2268   BoolTest::mask best_btest = BoolTest::illegal;
  2269   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  2270     Node* cmp = cmps[cmpn];
  2271     if (cmp == NULL)  continue;
  2272     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
  2273       Node* bol = cmp->fast_out(j);
  2274       if (!bol->is_Bool())  continue;
  2275       BoolTest::mask btest = bol->as_Bool()->_test._test;
  2276       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
  2277       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
  2278       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
  2279         best_bol   = bol->as_Bool();
  2280         best_btest = btest;
  2285   Node* answer_if_true  = NULL;
  2286   Node* answer_if_false = NULL;
  2287   switch (best_btest) {
  2288   default:
  2289     if (cmpxy == NULL)
  2290       cmpxy = ideal_cmpxy;
  2291     best_bol = _gvn.transform(new(C) BoolNode(cmpxy, BoolTest::lt));
  2292     // and fall through:
  2293   case BoolTest::lt:          // x < y
  2294   case BoolTest::le:          // x <= y
  2295     answer_if_true  = (want_max ? yvalue : xvalue);
  2296     answer_if_false = (want_max ? xvalue : yvalue);
  2297     break;
  2298   case BoolTest::gt:          // x > y
  2299   case BoolTest::ge:          // x >= y
  2300     answer_if_true  = (want_max ? xvalue : yvalue);
  2301     answer_if_false = (want_max ? yvalue : xvalue);
  2302     break;
  2305   jint hi, lo;
  2306   if (want_max) {
  2307     // We can sharpen the minimum.
  2308     hi = MAX2(txvalue->_hi, tyvalue->_hi);
  2309     lo = MAX2(txvalue->_lo, tyvalue->_lo);
  2310   } else {
  2311     // We can sharpen the maximum.
  2312     hi = MIN2(txvalue->_hi, tyvalue->_hi);
  2313     lo = MIN2(txvalue->_lo, tyvalue->_lo);
  2316   // Use a flow-free graph structure, to avoid creating excess control edges
  2317   // which could hinder other optimizations.
  2318   // Since Math.min/max is often used with arraycopy, we want
  2319   // tightly_coupled_allocation to be able to see beyond min/max expressions.
  2320   Node* cmov = CMoveNode::make(C, NULL, best_bol,
  2321                                answer_if_false, answer_if_true,
  2322                                TypeInt::make(lo, hi, widen));
  2324   return _gvn.transform(cmov);
  2326   /*
  2327   // This is not as desirable as it may seem, since Min and Max
  2328   // nodes do not have a full set of optimizations.
  2329   // And they would interfere, anyway, with 'if' optimizations
  2330   // and with CMoveI canonical forms.
  2331   switch (id) {
  2332   case vmIntrinsics::_min:
  2333     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
  2334   case vmIntrinsics::_max:
  2335     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
  2336   default:
  2337     ShouldNotReachHere();
  2339   */
  2342 inline int
  2343 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
  2344   const TypePtr* base_type = TypePtr::NULL_PTR;
  2345   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
  2346   if (base_type == NULL) {
  2347     // Unknown type.
  2348     return Type::AnyPtr;
  2349   } else if (base_type == TypePtr::NULL_PTR) {
  2350     // Since this is a NULL+long form, we have to switch to a rawptr.
  2351     base   = _gvn.transform(new (C) CastX2PNode(offset));
  2352     offset = MakeConX(0);
  2353     return Type::RawPtr;
  2354   } else if (base_type->base() == Type::RawPtr) {
  2355     return Type::RawPtr;
  2356   } else if (base_type->isa_oopptr()) {
  2357     // Base is never null => always a heap address.
  2358     if (base_type->ptr() == TypePtr::NotNull) {
  2359       return Type::OopPtr;
  2361     // Offset is small => always a heap address.
  2362     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
  2363     if (offset_type != NULL &&
  2364         base_type->offset() == 0 &&     // (should always be?)
  2365         offset_type->_lo >= 0 &&
  2366         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
  2367       return Type::OopPtr;
  2369     // Otherwise, it might either be oop+off or NULL+addr.
  2370     return Type::AnyPtr;
  2371   } else {
  2372     // No information:
  2373     return Type::AnyPtr;
  2377 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
  2378   int kind = classify_unsafe_addr(base, offset);
  2379   if (kind == Type::RawPtr) {
  2380     return basic_plus_adr(top(), base, offset);
  2381   } else {
  2382     return basic_plus_adr(base, offset);
  2386 //--------------------------inline_number_methods-----------------------------
  2387 // inline int     Integer.numberOfLeadingZeros(int)
  2388 // inline int        Long.numberOfLeadingZeros(long)
  2389 //
  2390 // inline int     Integer.numberOfTrailingZeros(int)
  2391 // inline int        Long.numberOfTrailingZeros(long)
  2392 //
  2393 // inline int     Integer.bitCount(int)
  2394 // inline int        Long.bitCount(long)
  2395 //
  2396 // inline char  Character.reverseBytes(char)
  2397 // inline short     Short.reverseBytes(short)
  2398 // inline int     Integer.reverseBytes(int)
  2399 // inline long       Long.reverseBytes(long)
  2400 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
  2401   Node* arg = argument(0);
  2402   Node* n = NULL;
  2403   switch (id) {
  2404   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new (C) CountLeadingZerosINode( arg);  break;
  2405   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new (C) CountLeadingZerosLNode( arg);  break;
  2406   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new (C) CountTrailingZerosINode(arg);  break;
  2407   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new (C) CountTrailingZerosLNode(arg);  break;
  2408   case vmIntrinsics::_bitCount_i:               n = new (C) PopCountINode(          arg);  break;
  2409   case vmIntrinsics::_bitCount_l:               n = new (C) PopCountLNode(          arg);  break;
  2410   case vmIntrinsics::_reverseBytes_c:           n = new (C) ReverseBytesUSNode(0,   arg);  break;
  2411   case vmIntrinsics::_reverseBytes_s:           n = new (C) ReverseBytesSNode( 0,   arg);  break;
  2412   case vmIntrinsics::_reverseBytes_i:           n = new (C) ReverseBytesINode( 0,   arg);  break;
  2413   case vmIntrinsics::_reverseBytes_l:           n = new (C) ReverseBytesLNode( 0,   arg);  break;
  2414   default:  fatal_unexpected_iid(id);  break;
  2416   set_result(_gvn.transform(n));
  2417   return true;
  2420 //----------------------------inline_unsafe_access----------------------------
  2422 const static BasicType T_ADDRESS_HOLDER = T_LONG;
  2424 // Helper that guards and inserts a pre-barrier.
  2425 void LibraryCallKit::insert_pre_barrier(Node* base_oop, Node* offset,
  2426                                         Node* pre_val, bool need_mem_bar) {
  2427   // We could be accessing the referent field of a reference object. If so, when G1
  2428   // is enabled, we need to log the value in the referent field in an SATB buffer.
  2429   // This routine performs some compile time filters and generates suitable
  2430   // runtime filters that guard the pre-barrier code.
  2431   // Also add memory barrier for non volatile load from the referent field
  2432   // to prevent commoning of loads across safepoint.
  2433   if (!UseG1GC && !need_mem_bar)
  2434     return;
  2436   // Some compile time checks.
  2438   // If offset is a constant, is it java_lang_ref_Reference::_reference_offset?
  2439   const TypeX* otype = offset->find_intptr_t_type();
  2440   if (otype != NULL && otype->is_con() &&
  2441       otype->get_con() != java_lang_ref_Reference::referent_offset) {
  2442     // Constant offset but not the reference_offset so just return
  2443     return;
  2446   // We only need to generate the runtime guards for instances.
  2447   const TypeOopPtr* btype = base_oop->bottom_type()->isa_oopptr();
  2448   if (btype != NULL) {
  2449     if (btype->isa_aryptr()) {
  2450       // Array type so nothing to do
  2451       return;
  2454     const TypeInstPtr* itype = btype->isa_instptr();
  2455     if (itype != NULL) {
  2456       // Can the klass of base_oop be statically determined to be
  2457       // _not_ a sub-class of Reference and _not_ Object?
  2458       ciKlass* klass = itype->klass();
  2459       if ( klass->is_loaded() &&
  2460           !klass->is_subtype_of(env()->Reference_klass()) &&
  2461           !env()->Object_klass()->is_subtype_of(klass)) {
  2462         return;
  2467   // The compile time filters did not reject base_oop/offset so
  2468   // we need to generate the following runtime filters
  2469   //
  2470   // if (offset == java_lang_ref_Reference::_reference_offset) {
  2471   //   if (instance_of(base, java.lang.ref.Reference)) {
  2472   //     pre_barrier(_, pre_val, ...);
  2473   //   }
  2474   // }
  2476   float likely   = PROB_LIKELY(  0.999);
  2477   float unlikely = PROB_UNLIKELY(0.999);
  2479   IdealKit ideal(this);
  2480 #define __ ideal.
  2482   Node* referent_off = __ ConX(java_lang_ref_Reference::referent_offset);
  2484   __ if_then(offset, BoolTest::eq, referent_off, unlikely); {
  2485       // Update graphKit memory and control from IdealKit.
  2486       sync_kit(ideal);
  2488       Node* ref_klass_con = makecon(TypeKlassPtr::make(env()->Reference_klass()));
  2489       Node* is_instof = gen_instanceof(base_oop, ref_klass_con);
  2491       // Update IdealKit memory and control from graphKit.
  2492       __ sync_kit(this);
  2494       Node* one = __ ConI(1);
  2495       // is_instof == 0 if base_oop == NULL
  2496       __ if_then(is_instof, BoolTest::eq, one, unlikely); {
  2498         // Update graphKit from IdeakKit.
  2499         sync_kit(ideal);
  2501         // Use the pre-barrier to record the value in the referent field
  2502         pre_barrier(false /* do_load */,
  2503                     __ ctrl(),
  2504                     NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
  2505                     pre_val /* pre_val */,
  2506                     T_OBJECT);
  2507         if (need_mem_bar) {
  2508           // Add memory barrier to prevent commoning reads from this field
  2509           // across safepoint since GC can change its value.
  2510           insert_mem_bar(Op_MemBarCPUOrder);
  2512         // Update IdealKit from graphKit.
  2513         __ sync_kit(this);
  2515       } __ end_if(); // _ref_type != ref_none
  2516   } __ end_if(); // offset == referent_offset
  2518   // Final sync IdealKit and GraphKit.
  2519   final_sync(ideal);
  2520 #undef __
  2524 // Interpret Unsafe.fieldOffset cookies correctly:
  2525 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
  2527 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type, bool is_native_ptr) {
  2528   // Attempt to infer a sharper value type from the offset and base type.
  2529   ciKlass* sharpened_klass = NULL;
  2531   // See if it is an instance field, with an object type.
  2532   if (alias_type->field() != NULL) {
  2533     assert(!is_native_ptr, "native pointer op cannot use a java address");
  2534     if (alias_type->field()->type()->is_klass()) {
  2535       sharpened_klass = alias_type->field()->type()->as_klass();
  2539   // See if it is a narrow oop array.
  2540   if (adr_type->isa_aryptr()) {
  2541     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
  2542       const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
  2543       if (elem_type != NULL) {
  2544         sharpened_klass = elem_type->klass();
  2549   // The sharpened class might be unloaded if there is no class loader
  2550   // contraint in place.
  2551   if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
  2552     const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
  2554 #ifndef PRODUCT
  2555     if (C->print_intrinsics() || C->print_inlining()) {
  2556       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
  2557       tty->print("  sharpened value: ");  tjp->dump();      tty->cr();
  2559 #endif
  2560     // Sharpen the value type.
  2561     return tjp;
  2563   return NULL;
  2566 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile, bool unaligned) {
  2567   if (callee()->is_static())  return false;  // caller must have the capability!
  2568   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
  2570 #ifndef PRODUCT
  2572     ResourceMark rm;
  2573     // Check the signatures.
  2574     ciSignature* sig = callee()->signature();
  2575 #ifdef ASSERT
  2576     if (!is_store) {
  2577       // Object getObject(Object base, int/long offset), etc.
  2578       BasicType rtype = sig->return_type()->basic_type();
  2579       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
  2580           rtype = T_ADDRESS;  // it is really a C void*
  2581       assert(rtype == type, "getter must return the expected value");
  2582       if (!is_native_ptr) {
  2583         assert(sig->count() == 2, "oop getter has 2 arguments");
  2584         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
  2585         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
  2586       } else {
  2587         assert(sig->count() == 1, "native getter has 1 argument");
  2588         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
  2590     } else {
  2591       // void putObject(Object base, int/long offset, Object x), etc.
  2592       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
  2593       if (!is_native_ptr) {
  2594         assert(sig->count() == 3, "oop putter has 3 arguments");
  2595         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
  2596         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
  2597       } else {
  2598         assert(sig->count() == 2, "native putter has 2 arguments");
  2599         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
  2601       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
  2602       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
  2603         vtype = T_ADDRESS;  // it is really a C void*
  2604       assert(vtype == type, "putter must accept the expected value");
  2606 #endif // ASSERT
  2608 #endif //PRODUCT
  2610   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2612   Node* receiver = argument(0);  // type: oop
  2614   // Build address expression.  See the code in inline_unsafe_prefetch.
  2615   Node* adr;
  2616   Node* heap_base_oop = top();
  2617   Node* offset = top();
  2618   Node* val;
  2620   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2621   Node* base = argument(1);  // type: oop
  2623   if (!is_native_ptr) {
  2624     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2625     offset = argument(2);  // type: long
  2626     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2627     // to be plain byte offsets, which are also the same as those accepted
  2628     // by oopDesc::field_base.
  2629     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2630            "fieldOffset must be byte-scaled");
  2631     // 32-bit machines ignore the high half!
  2632     offset = ConvL2X(offset);
  2633     adr = make_unsafe_address(base, offset);
  2634     heap_base_oop = base;
  2635     val = is_store ? argument(4) : NULL;
  2636   } else {
  2637     Node* ptr = argument(1);  // type: long
  2638     ptr = ConvL2X(ptr);  // adjust Java long to machine word
  2639     adr = make_unsafe_address(NULL, ptr);
  2640     val = is_store ? argument(3) : NULL;
  2643   if ((_gvn.type(base)->isa_ptr() == TypePtr::NULL_PTR) && type == T_OBJECT) {
  2644     return false; // off-heap oop accesses are not supported
  2647   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2649   // Try to categorize the address.
  2650   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2651   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2653   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
  2654       alias_type->adr_type() == TypeAryPtr::RANGE) {
  2655     return false; // not supported
  2658   bool mismatched = false;
  2659   BasicType bt = alias_type->basic_type();
  2660   if (bt != T_ILLEGAL) {
  2661     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
  2662     if (bt == T_BYTE && adr_type->isa_aryptr()) {
  2663       // Alias type doesn't differentiate between byte[] and boolean[]).
  2664       // Use address type to get the element type.
  2665       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
  2667     if (bt == T_ARRAY || bt == T_NARROWOOP) {
  2668       // accessing an array field with getObject is not a mismatch
  2669       bt = T_OBJECT;
  2671     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
  2672       // Don't intrinsify mismatched object accesses
  2673       return false;
  2675     mismatched = (bt != type);
  2678   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
  2680   // First guess at the value type.
  2681   const Type *value_type = Type::get_const_basic_type(type);
  2683   // We will need memory barriers unless we can determine a unique
  2684   // alias category for this reference.  (Note:  If for some reason
  2685   // the barriers get omitted and the unsafe reference begins to "pollute"
  2686   // the alias analysis of the rest of the graph, either Compile::can_alias
  2687   // or Compile::must_alias will throw a diagnostic assert.)
  2688   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
  2690   // If we are reading the value of the referent field of a Reference
  2691   // object (either by using Unsafe directly or through reflection)
  2692   // then, if G1 is enabled, we need to record the referent in an
  2693   // SATB log buffer using the pre-barrier mechanism.
  2694   // Also we need to add memory barrier to prevent commoning reads
  2695   // from this field across safepoint since GC can change its value.
  2696   bool need_read_barrier = !is_native_ptr && !is_store &&
  2697                            offset != top() && heap_base_oop != top();
  2699   if (!is_store && type == T_OBJECT) {
  2700     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type, is_native_ptr);
  2701     if (tjp != NULL) {
  2702       value_type = tjp;
  2706   receiver = null_check(receiver);
  2707   if (stopped()) {
  2708     return true;
  2710   // Heap pointers get a null-check from the interpreter,
  2711   // as a courtesy.  However, this is not guaranteed by Unsafe,
  2712   // and it is not possible to fully distinguish unintended nulls
  2713   // from intended ones in this API.
  2715   if (is_volatile) {
  2716     // We need to emit leading and trailing CPU membars (see below) in
  2717     // addition to memory membars when is_volatile. This is a little
  2718     // too strong, but avoids the need to insert per-alias-type
  2719     // volatile membars (for stores; compare Parse::do_put_xxx), which
  2720     // we cannot do effectively here because we probably only have a
  2721     // rough approximation of type.
  2722     need_mem_bar = true;
  2723     // For Stores, place a memory ordering barrier now.
  2724     if (is_store) {
  2725       insert_mem_bar(Op_MemBarRelease);
  2726     } else {
  2727       if (support_IRIW_for_not_multiple_copy_atomic_cpu) {
  2728         insert_mem_bar(Op_MemBarVolatile);
  2733   // Memory barrier to prevent normal and 'unsafe' accesses from
  2734   // bypassing each other.  Happens after null checks, so the
  2735   // exception paths do not take memory state from the memory barrier,
  2736   // so there's no problems making a strong assert about mixing users
  2737   // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
  2738   // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
  2739   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2741   if (!is_store) {
  2742     MemNode::MemOrd mo = is_volatile ? MemNode::acquire : MemNode::unordered;
  2743     // To be valid, unsafe loads may depend on other conditions than
  2744     // the one that guards them: pin the Load node
  2745     Node* p = make_load(control(), adr, value_type, type, adr_type, mo, LoadNode::Pinned, is_volatile, unaligned, mismatched);
  2746     // load value
  2747     switch (type) {
  2748     case T_BOOLEAN:
  2749     case T_CHAR:
  2750     case T_BYTE:
  2751     case T_SHORT:
  2752     case T_INT:
  2753     case T_LONG:
  2754     case T_FLOAT:
  2755     case T_DOUBLE:
  2756       break;
  2757     case T_OBJECT:
  2758       if (need_read_barrier) {
  2759         insert_pre_barrier(heap_base_oop, offset, p, !(is_volatile || need_mem_bar));
  2761       break;
  2762     case T_ADDRESS:
  2763       // Cast to an int type.
  2764       p = _gvn.transform(new (C) CastP2XNode(NULL, p));
  2765       p = ConvX2UL(p);
  2766       break;
  2767     default:
  2768       fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
  2769       break;
  2771     // The load node has the control of the preceding MemBarCPUOrder.  All
  2772     // following nodes will have the control of the MemBarCPUOrder inserted at
  2773     // the end of this method.  So, pushing the load onto the stack at a later
  2774     // point is fine.
  2775     set_result(p);
  2776   } else {
  2777     // place effect of store into memory
  2778     switch (type) {
  2779     case T_DOUBLE:
  2780       val = dstore_rounding(val);
  2781       break;
  2782     case T_ADDRESS:
  2783       // Repackage the long as a pointer.
  2784       val = ConvL2X(val);
  2785       val = _gvn.transform(new (C) CastX2PNode(val));
  2786       break;
  2789     MemNode::MemOrd mo = is_volatile ? MemNode::release : MemNode::unordered;
  2790     if (type == T_OBJECT ) {
  2791       (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type, mo, mismatched);
  2792     } else {
  2793       (void) store_to_memory(control(), adr, val, type, adr_type, mo, is_volatile, unaligned, mismatched);
  2797   if (is_volatile) {
  2798     if (!is_store) {
  2799       insert_mem_bar(Op_MemBarAcquire);
  2800     } else {
  2801       if (!support_IRIW_for_not_multiple_copy_atomic_cpu) {
  2802         insert_mem_bar(Op_MemBarVolatile);
  2807   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2809   return true;
  2812 //----------------------------inline_unsafe_prefetch----------------------------
  2814 bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
  2815 #ifndef PRODUCT
  2817     ResourceMark rm;
  2818     // Check the signatures.
  2819     ciSignature* sig = callee()->signature();
  2820 #ifdef ASSERT
  2821     // Object getObject(Object base, int/long offset), etc.
  2822     BasicType rtype = sig->return_type()->basic_type();
  2823     if (!is_native_ptr) {
  2824       assert(sig->count() == 2, "oop prefetch has 2 arguments");
  2825       assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
  2826       assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
  2827     } else {
  2828       assert(sig->count() == 1, "native prefetch has 1 argument");
  2829       assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
  2831 #endif // ASSERT
  2833 #endif // !PRODUCT
  2835   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2837   const int idx = is_static ? 0 : 1;
  2838   if (!is_static) {
  2839     null_check_receiver();
  2840     if (stopped()) {
  2841       return true;
  2845   // Build address expression.  See the code in inline_unsafe_access.
  2846   Node *adr;
  2847   if (!is_native_ptr) {
  2848     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2849     Node* base   = argument(idx + 0);  // type: oop
  2850     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2851     Node* offset = argument(idx + 1);  // type: long
  2852     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2853     // to be plain byte offsets, which are also the same as those accepted
  2854     // by oopDesc::field_base.
  2855     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2856            "fieldOffset must be byte-scaled");
  2857     // 32-bit machines ignore the high half!
  2858     offset = ConvL2X(offset);
  2859     adr = make_unsafe_address(base, offset);
  2860   } else {
  2861     Node* ptr = argument(idx + 0);  // type: long
  2862     ptr = ConvL2X(ptr);  // adjust Java long to machine word
  2863     adr = make_unsafe_address(NULL, ptr);
  2866   // Generate the read or write prefetch
  2867   Node *prefetch;
  2868   if (is_store) {
  2869     prefetch = new (C) PrefetchWriteNode(i_o(), adr);
  2870   } else {
  2871     prefetch = new (C) PrefetchReadNode(i_o(), adr);
  2873   prefetch->init_req(0, control());
  2874   set_i_o(_gvn.transform(prefetch));
  2876   return true;
  2879 //----------------------------inline_unsafe_load_store----------------------------
  2880 // This method serves a couple of different customers (depending on LoadStoreKind):
  2881 //
  2882 // LS_cmpxchg:
  2883 //   public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
  2884 //   public final native boolean compareAndSwapInt(   Object o, long offset, int    expected, int    x);
  2885 //   public final native boolean compareAndSwapLong(  Object o, long offset, long   expected, long   x);
  2886 //
  2887 // LS_xadd:
  2888 //   public int  getAndAddInt( Object o, long offset, int  delta)
  2889 //   public long getAndAddLong(Object o, long offset, long delta)
  2890 //
  2891 // LS_xchg:
  2892 //   int    getAndSet(Object o, long offset, int    newValue)
  2893 //   long   getAndSet(Object o, long offset, long   newValue)
  2894 //   Object getAndSet(Object o, long offset, Object newValue)
  2895 //
  2896 bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind) {
  2897   // This basic scheme here is the same as inline_unsafe_access, but
  2898   // differs in enough details that combining them would make the code
  2899   // overly confusing.  (This is a true fact! I originally combined
  2900   // them, but even I was confused by it!) As much code/comments as
  2901   // possible are retained from inline_unsafe_access though to make
  2902   // the correspondences clearer. - dl
  2904   if (callee()->is_static())  return false;  // caller must have the capability!
  2906 #ifndef PRODUCT
  2907   BasicType rtype;
  2909     ResourceMark rm;
  2910     // Check the signatures.
  2911     ciSignature* sig = callee()->signature();
  2912     rtype = sig->return_type()->basic_type();
  2913     if (kind == LS_xadd || kind == LS_xchg) {
  2914       // Check the signatures.
  2915 #ifdef ASSERT
  2916       assert(rtype == type, "get and set must return the expected type");
  2917       assert(sig->count() == 3, "get and set has 3 arguments");
  2918       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
  2919       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
  2920       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
  2921 #endif // ASSERT
  2922     } else if (kind == LS_cmpxchg) {
  2923       // Check the signatures.
  2924 #ifdef ASSERT
  2925       assert(rtype == T_BOOLEAN, "CAS must return boolean");
  2926       assert(sig->count() == 4, "CAS has 4 arguments");
  2927       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
  2928       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
  2929 #endif // ASSERT
  2930     } else {
  2931       ShouldNotReachHere();
  2934 #endif //PRODUCT
  2936   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2938   // Get arguments:
  2939   Node* receiver = NULL;
  2940   Node* base     = NULL;
  2941   Node* offset   = NULL;
  2942   Node* oldval   = NULL;
  2943   Node* newval   = NULL;
  2944   if (kind == LS_cmpxchg) {
  2945     const bool two_slot_type = type2size[type] == 2;
  2946     receiver = argument(0);  // type: oop
  2947     base     = argument(1);  // type: oop
  2948     offset   = argument(2);  // type: long
  2949     oldval   = argument(4);  // type: oop, int, or long
  2950     newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
  2951   } else if (kind == LS_xadd || kind == LS_xchg){
  2952     receiver = argument(0);  // type: oop
  2953     base     = argument(1);  // type: oop
  2954     offset   = argument(2);  // type: long
  2955     oldval   = NULL;
  2956     newval   = argument(4);  // type: oop, int, or long
  2959   // Build field offset expression.
  2960   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2961   // to be plain byte offsets, which are also the same as those accepted
  2962   // by oopDesc::field_base.
  2963   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  2964   // 32-bit machines ignore the high half of long offsets
  2965   offset = ConvL2X(offset);
  2966   Node* adr = make_unsafe_address(base, offset);
  2967   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2969   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2970   BasicType bt = alias_type->basic_type();
  2971   if (bt != T_ILLEGAL &&
  2972       ((bt == T_OBJECT || bt == T_ARRAY) != (type == T_OBJECT))) {
  2973     // Don't intrinsify mismatched object accesses.
  2974     return false;
  2977   // For CAS, unlike inline_unsafe_access, there seems no point in
  2978   // trying to refine types. Just use the coarse types here.
  2979   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2980   const Type *value_type = Type::get_const_basic_type(type);
  2982   if (kind == LS_xchg && type == T_OBJECT) {
  2983     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
  2984     if (tjp != NULL) {
  2985       value_type = tjp;
  2989   // Null check receiver.
  2990   receiver = null_check(receiver);
  2991   if (stopped()) {
  2992     return true;
  2995   int alias_idx = C->get_alias_index(adr_type);
  2997   // Memory-model-wise, a LoadStore acts like a little synchronized
  2998   // block, so needs barriers on each side.  These don't translate
  2999   // into actual barriers on most machines, but we still need rest of
  3000   // compiler to respect ordering.
  3002   insert_mem_bar(Op_MemBarRelease);
  3003   insert_mem_bar(Op_MemBarCPUOrder);
  3005   // 4984716: MemBars must be inserted before this
  3006   //          memory node in order to avoid a false
  3007   //          dependency which will confuse the scheduler.
  3008   Node *mem = memory(alias_idx);
  3010   // For now, we handle only those cases that actually exist: ints,
  3011   // longs, and Object. Adding others should be straightforward.
  3012   Node* load_store = NULL;
  3013   switch(type) {
  3014   case T_INT:
  3015     if (kind == LS_xadd) {
  3016       load_store = _gvn.transform(new (C) GetAndAddINode(control(), mem, adr, newval, adr_type));
  3017     } else if (kind == LS_xchg) {
  3018       load_store = _gvn.transform(new (C) GetAndSetINode(control(), mem, adr, newval, adr_type));
  3019     } else if (kind == LS_cmpxchg) {
  3020       load_store = _gvn.transform(new (C) CompareAndSwapINode(control(), mem, adr, newval, oldval));
  3021     } else {
  3022       ShouldNotReachHere();
  3024     break;
  3025   case T_LONG:
  3026     if (kind == LS_xadd) {
  3027       load_store = _gvn.transform(new (C) GetAndAddLNode(control(), mem, adr, newval, adr_type));
  3028     } else if (kind == LS_xchg) {
  3029       load_store = _gvn.transform(new (C) GetAndSetLNode(control(), mem, adr, newval, adr_type));
  3030     } else if (kind == LS_cmpxchg) {
  3031       load_store = _gvn.transform(new (C) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
  3032     } else {
  3033       ShouldNotReachHere();
  3035     break;
  3036   case T_OBJECT:
  3037     // Transformation of a value which could be NULL pointer (CastPP #NULL)
  3038     // could be delayed during Parse (for example, in adjust_map_after_if()).
  3039     // Execute transformation here to avoid barrier generation in such case.
  3040     if (_gvn.type(newval) == TypePtr::NULL_PTR)
  3041       newval = _gvn.makecon(TypePtr::NULL_PTR);
  3043     // Reference stores need a store barrier.
  3044     if (kind == LS_xchg) {
  3045       // If pre-barrier must execute before the oop store, old value will require do_load here.
  3046       if (!can_move_pre_barrier()) {
  3047         pre_barrier(true /* do_load*/,
  3048                     control(), base, adr, alias_idx, newval, value_type->make_oopptr(),
  3049                     NULL /* pre_val*/,
  3050                     T_OBJECT);
  3051       } // Else move pre_barrier to use load_store value, see below.
  3052     } else if (kind == LS_cmpxchg) {
  3053       // Same as for newval above:
  3054       if (_gvn.type(oldval) == TypePtr::NULL_PTR) {
  3055         oldval = _gvn.makecon(TypePtr::NULL_PTR);
  3057       // The only known value which might get overwritten is oldval.
  3058       pre_barrier(false /* do_load */,
  3059                   control(), NULL, NULL, max_juint, NULL, NULL,
  3060                   oldval /* pre_val */,
  3061                   T_OBJECT);
  3062     } else {
  3063       ShouldNotReachHere();
  3066 #ifdef _LP64
  3067     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  3068       Node *newval_enc = _gvn.transform(new (C) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
  3069       if (kind == LS_xchg) {
  3070         load_store = _gvn.transform(new (C) GetAndSetNNode(control(), mem, adr,
  3071                                                            newval_enc, adr_type, value_type->make_narrowoop()));
  3072       } else {
  3073         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
  3074         Node *oldval_enc = _gvn.transform(new (C) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
  3075         load_store = _gvn.transform(new (C) CompareAndSwapNNode(control(), mem, adr,
  3076                                                                 newval_enc, oldval_enc));
  3078     } else
  3079 #endif
  3081       if (kind == LS_xchg) {
  3082         load_store = _gvn.transform(new (C) GetAndSetPNode(control(), mem, adr, newval, adr_type, value_type->is_oopptr()));
  3083       } else {
  3084         assert(kind == LS_cmpxchg, "wrong LoadStore operation");
  3085         load_store = _gvn.transform(new (C) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
  3088     post_barrier(control(), load_store, base, adr, alias_idx, newval, T_OBJECT, true);
  3089     break;
  3090   default:
  3091     fatal(err_msg_res("unexpected type %d: %s", type, type2name(type)));
  3092     break;
  3095   // SCMemProjNodes represent the memory state of a LoadStore. Their
  3096   // main role is to prevent LoadStore nodes from being optimized away
  3097   // when their results aren't used.
  3098   Node* proj = _gvn.transform(new (C) SCMemProjNode(load_store));
  3099   set_memory(proj, alias_idx);
  3101   if (type == T_OBJECT && kind == LS_xchg) {
  3102 #ifdef _LP64
  3103     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  3104       load_store = _gvn.transform(new (C) DecodeNNode(load_store, load_store->get_ptr_type()));
  3106 #endif
  3107     if (can_move_pre_barrier()) {
  3108       // Don't need to load pre_val. The old value is returned by load_store.
  3109       // The pre_barrier can execute after the xchg as long as no safepoint
  3110       // gets inserted between them.
  3111       pre_barrier(false /* do_load */,
  3112                   control(), NULL, NULL, max_juint, NULL, NULL,
  3113                   load_store /* pre_val */,
  3114                   T_OBJECT);
  3118   // Add the trailing membar surrounding the access
  3119   insert_mem_bar(Op_MemBarCPUOrder);
  3120   insert_mem_bar(Op_MemBarAcquire);
  3122   assert(type2size[load_store->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
  3123   set_result(load_store);
  3124   return true;
  3127 //----------------------------inline_unsafe_ordered_store----------------------
  3128 // public native void sun.misc.Unsafe.putOrderedObject(Object o, long offset, Object x);
  3129 // public native void sun.misc.Unsafe.putOrderedInt(Object o, long offset, int x);
  3130 // public native void sun.misc.Unsafe.putOrderedLong(Object o, long offset, long x);
  3131 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
  3132   // This is another variant of inline_unsafe_access, differing in
  3133   // that it always issues store-store ("release") barrier and ensures
  3134   // store-atomicity (which only matters for "long").
  3136   if (callee()->is_static())  return false;  // caller must have the capability!
  3138 #ifndef PRODUCT
  3140     ResourceMark rm;
  3141     // Check the signatures.
  3142     ciSignature* sig = callee()->signature();
  3143 #ifdef ASSERT
  3144     BasicType rtype = sig->return_type()->basic_type();
  3145     assert(rtype == T_VOID, "must return void");
  3146     assert(sig->count() == 3, "has 3 arguments");
  3147     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
  3148     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
  3149 #endif // ASSERT
  3151 #endif //PRODUCT
  3153   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  3155   // Get arguments:
  3156   Node* receiver = argument(0);  // type: oop
  3157   Node* base     = argument(1);  // type: oop
  3158   Node* offset   = argument(2);  // type: long
  3159   Node* val      = argument(4);  // type: oop, int, or long
  3161   // Null check receiver.
  3162   receiver = null_check(receiver);
  3163   if (stopped()) {
  3164     return true;
  3167   // Build field offset expression.
  3168   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  3169   // 32-bit machines ignore the high half of long offsets
  3170   offset = ConvL2X(offset);
  3171   Node* adr = make_unsafe_address(base, offset);
  3172   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  3173   const Type *value_type = Type::get_const_basic_type(type);
  3174   Compile::AliasType* alias_type = C->alias_type(adr_type);
  3176   insert_mem_bar(Op_MemBarRelease);
  3177   insert_mem_bar(Op_MemBarCPUOrder);
  3178   // Ensure that the store is atomic for longs:
  3179   const bool require_atomic_access = true;
  3180   Node* store;
  3181   if (type == T_OBJECT) // reference stores need a store barrier.
  3182     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type, MemNode::release);
  3183   else {
  3184     store = store_to_memory(control(), adr, val, type, adr_type, MemNode::release, require_atomic_access);
  3186   insert_mem_bar(Op_MemBarCPUOrder);
  3187   return true;
  3190 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
  3191   // Regardless of form, don't allow previous ld/st to move down,
  3192   // then issue acquire, release, or volatile mem_bar.
  3193   insert_mem_bar(Op_MemBarCPUOrder);
  3194   switch(id) {
  3195     case vmIntrinsics::_loadFence:
  3196       insert_mem_bar(Op_LoadFence);
  3197       return true;
  3198     case vmIntrinsics::_storeFence:
  3199       insert_mem_bar(Op_StoreFence);
  3200       return true;
  3201     case vmIntrinsics::_fullFence:
  3202       insert_mem_bar(Op_MemBarVolatile);
  3203       return true;
  3204     default:
  3205       fatal_unexpected_iid(id);
  3206       return false;
  3210 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
  3211   if (!kls->is_Con()) {
  3212     return true;
  3214   const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
  3215   if (klsptr == NULL) {
  3216     return true;
  3218   ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
  3219   // don't need a guard for a klass that is already initialized
  3220   return !ik->is_initialized();
  3223 //----------------------------inline_unsafe_allocate---------------------------
  3224 // public native Object sun.misc.Unsafe.allocateInstance(Class<?> cls);
  3225 bool LibraryCallKit::inline_unsafe_allocate() {
  3226   if (callee()->is_static())  return false;  // caller must have the capability!
  3228   null_check_receiver();  // null-check, then ignore
  3229   Node* cls = null_check(argument(1));
  3230   if (stopped())  return true;
  3232   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
  3233   kls = null_check(kls);
  3234   if (stopped())  return true;  // argument was like int.class
  3236   Node* test = NULL;
  3237   if (LibraryCallKit::klass_needs_init_guard(kls)) {
  3238     // Note:  The argument might still be an illegal value like
  3239     // Serializable.class or Object[].class.   The runtime will handle it.
  3240     // But we must make an explicit check for initialization.
  3241     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
  3242     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
  3243     // can generate code to load it as unsigned byte.
  3244     Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
  3245     Node* bits = intcon(InstanceKlass::fully_initialized);
  3246     test = _gvn.transform(new (C) SubINode(inst, bits));
  3247     // The 'test' is non-zero if we need to take a slow path.
  3250   Node* obj = new_instance(kls, test);
  3251   set_result(obj);
  3252   return true;
  3255 #ifdef JFR_HAVE_INTRINSICS
  3256 /*
  3257  * oop -> myklass
  3258  * myklass->trace_id |= USED
  3259  * return myklass->trace_id & ~0x3
  3260  */
  3261 bool LibraryCallKit::inline_native_classID() {
  3262   Node* cls = null_check(argument(0), T_OBJECT);
  3263   Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
  3264   kls = null_check(kls, T_OBJECT);
  3266   ByteSize offset = KLASS_TRACE_ID_OFFSET;
  3267   Node* insp = basic_plus_adr(kls, in_bytes(offset));
  3268   Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
  3270   Node* clsused = longcon(0x01l); // set the class bit
  3271   Node* orl = _gvn.transform(new (C) OrLNode(tvalue, clsused));
  3272   const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
  3273   store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
  3275 #ifdef TRACE_ID_META_BITS
  3276   Node* mbits = longcon(~TRACE_ID_META_BITS);
  3277   tvalue = _gvn.transform(new (C) AndLNode(tvalue, mbits));
  3278 #endif
  3279 #ifdef TRACE_ID_SHIFT
  3280   Node* cbits = intcon(TRACE_ID_SHIFT);
  3281   tvalue = _gvn.transform(new (C) URShiftLNode(tvalue, cbits));
  3282 #endif
  3284   set_result(tvalue);
  3285   return true;
  3288 bool LibraryCallKit::inline_native_getEventWriter() {
  3289   Node* tls_ptr = _gvn.transform(new (C) ThreadLocalNode());
  3291   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,
  3292                                   in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR)
  3293                                   );
  3295   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
  3297   Node* jobj_cmp_null = _gvn.transform( new (C) CmpPNode(jobj, null()) );
  3298   Node* test_jobj_eq_null  = _gvn.transform( new (C) BoolNode(jobj_cmp_null, BoolTest::eq) );
  3300   IfNode* iff_jobj_null =
  3301     create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);
  3303   enum { _normal_path = 1,
  3304          _null_path = 2,
  3305          PATH_LIMIT };
  3307   RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);
  3308   PhiNode*    result_val = new (C) PhiNode(result_rgn, TypePtr::BOTTOM);
  3310   Node* jobj_is_null = _gvn.transform(new (C) IfTrueNode(iff_jobj_null));
  3311   result_rgn->init_req(_null_path, jobj_is_null);
  3312   result_val->init_req(_null_path, null());
  3314   Node* jobj_is_not_null = _gvn.transform(new (C) IfFalseNode(iff_jobj_null));
  3315   result_rgn->init_req(_normal_path, jobj_is_not_null);
  3317   Node* res = make_load(jobj_is_not_null, jobj, TypeInstPtr::NOTNULL, T_OBJECT, MemNode::unordered);
  3318   result_val->init_req(_normal_path, res);
  3320   set_result(result_rgn, result_val);
  3322   return true;
  3324 #endif // JFR_HAVE_INTRINSICS
  3326 //------------------------inline_native_time_funcs--------------
  3327 // inline code for System.currentTimeMillis() and System.nanoTime()
  3328 // these have the same type and signature
  3329 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
  3330   const TypeFunc* tf = OptoRuntime::void_long_Type();
  3331   const TypePtr* no_memory_effects = NULL;
  3332   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
  3333   Node* value = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+0));
  3334 #ifdef ASSERT
  3335   Node* value_top = _gvn.transform(new (C) ProjNode(time, TypeFunc::Parms+1));
  3336   assert(value_top == top(), "second value must be top");
  3337 #endif
  3338   set_result(value);
  3339   return true;
  3342 //------------------------inline_native_currentThread------------------
  3343 bool LibraryCallKit::inline_native_currentThread() {
  3344   Node* junk = NULL;
  3345   set_result(generate_current_thread(junk));
  3346   return true;
  3349 //------------------------inline_native_isInterrupted------------------
  3350 // private native boolean java.lang.Thread.isInterrupted(boolean ClearInterrupted);
  3351 bool LibraryCallKit::inline_native_isInterrupted() {
  3352   // Add a fast path to t.isInterrupted(clear_int):
  3353   //   (t == Thread.current() &&
  3354   //    (!TLS._osthread._interrupted || WINDOWS_ONLY(false) NOT_WINDOWS(!clear_int)))
  3355   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
  3356   // So, in the common case that the interrupt bit is false,
  3357   // we avoid making a call into the VM.  Even if the interrupt bit
  3358   // is true, if the clear_int argument is false, we avoid the VM call.
  3359   // However, if the receiver is not currentThread, we must call the VM,
  3360   // because there must be some locking done around the operation.
  3362   // We only go to the fast case code if we pass two guards.
  3363   // Paths which do not pass are accumulated in the slow_region.
  3365   enum {
  3366     no_int_result_path   = 1, // t == Thread.current() && !TLS._osthread._interrupted
  3367     no_clear_result_path = 2, // t == Thread.current() &&  TLS._osthread._interrupted && !clear_int
  3368     slow_result_path     = 3, // slow path: t.isInterrupted(clear_int)
  3369     PATH_LIMIT
  3370   };
  3372   // Ensure that it's not possible to move the load of TLS._osthread._interrupted flag
  3373   // out of the function.
  3374   insert_mem_bar(Op_MemBarCPUOrder);
  3376   RegionNode* result_rgn = new (C) RegionNode(PATH_LIMIT);
  3377   PhiNode*    result_val = new (C) PhiNode(result_rgn, TypeInt::BOOL);
  3379   RegionNode* slow_region = new (C) RegionNode(1);
  3380   record_for_igvn(slow_region);
  3382   // (a) Receiving thread must be the current thread.
  3383   Node* rec_thr = argument(0);
  3384   Node* tls_ptr = NULL;
  3385   Node* cur_thr = generate_current_thread(tls_ptr);
  3386   Node* cmp_thr = _gvn.transform(new (C) CmpPNode(cur_thr, rec_thr));
  3387   Node* bol_thr = _gvn.transform(new (C) BoolNode(cmp_thr, BoolTest::ne));
  3389   generate_slow_guard(bol_thr, slow_region);
  3391   // (b) Interrupt bit on TLS must be false.
  3392   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
  3393   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
  3394   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
  3396   // Set the control input on the field _interrupted read to prevent it floating up.
  3397   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT, MemNode::unordered);
  3398   Node* cmp_bit = _gvn.transform(new (C) CmpINode(int_bit, intcon(0)));
  3399   Node* bol_bit = _gvn.transform(new (C) BoolNode(cmp_bit, BoolTest::ne));
  3401   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
  3403   // First fast path:  if (!TLS._interrupted) return false;
  3404   Node* false_bit = _gvn.transform(new (C) IfFalseNode(iff_bit));
  3405   result_rgn->init_req(no_int_result_path, false_bit);
  3406   result_val->init_req(no_int_result_path, intcon(0));
  3408   // drop through to next case
  3409   set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)));
  3411 #ifndef TARGET_OS_FAMILY_windows
  3412   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
  3413   Node* clr_arg = argument(1);
  3414   Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0)));
  3415   Node* bol_arg = _gvn.transform(new (C) BoolNode(cmp_arg, BoolTest::ne));
  3416   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
  3418   // Second fast path:  ... else if (!clear_int) return true;
  3419   Node* false_arg = _gvn.transform(new (C) IfFalseNode(iff_arg));
  3420   result_rgn->init_req(no_clear_result_path, false_arg);
  3421   result_val->init_req(no_clear_result_path, intcon(1));
  3423   // drop through to next case
  3424   set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)));
  3425 #else
  3426   // To return true on Windows you must read the _interrupted field
  3427   // and check the the event state i.e. take the slow path.
  3428 #endif // TARGET_OS_FAMILY_windows
  3430   // (d) Otherwise, go to the slow path.
  3431   slow_region->add_req(control());
  3432   set_control( _gvn.transform(slow_region));
  3434   if (stopped()) {
  3435     // There is no slow path.
  3436     result_rgn->init_req(slow_result_path, top());
  3437     result_val->init_req(slow_result_path, top());
  3438   } else {
  3439     // non-virtual because it is a private non-static
  3440     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
  3442     Node* slow_val = set_results_for_java_call(slow_call);
  3443     // this->control() comes from set_results_for_java_call
  3445     Node* fast_io  = slow_call->in(TypeFunc::I_O);
  3446     Node* fast_mem = slow_call->in(TypeFunc::Memory);
  3448     // These two phis are pre-filled with copies of of the fast IO and Memory
  3449     PhiNode* result_mem  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
  3450     PhiNode* result_io   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
  3452     result_rgn->init_req(slow_result_path, control());
  3453     result_io ->init_req(slow_result_path, i_o());
  3454     result_mem->init_req(slow_result_path, reset_memory());
  3455     result_val->init_req(slow_result_path, slow_val);
  3457     set_all_memory(_gvn.transform(result_mem));
  3458     set_i_o(       _gvn.transform(result_io));
  3461   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3462   set_result(result_rgn, result_val);
  3463   return true;
  3466 //---------------------------load_mirror_from_klass----------------------------
  3467 // Given a klass oop, load its java mirror (a java.lang.Class oop).
  3468 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
  3469   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
  3470   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
  3473 //-----------------------load_klass_from_mirror_common-------------------------
  3474 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
  3475 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
  3476 // and branch to the given path on the region.
  3477 // If never_see_null, take an uncommon trap on null, so we can optimistically
  3478 // compile for the non-null case.
  3479 // If the region is NULL, force never_see_null = true.
  3480 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
  3481                                                     bool never_see_null,
  3482                                                     RegionNode* region,
  3483                                                     int null_path,
  3484                                                     int offset) {
  3485   if (region == NULL)  never_see_null = true;
  3486   Node* p = basic_plus_adr(mirror, offset);
  3487   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  3488   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
  3489   Node* null_ctl = top();
  3490   kls = null_check_oop(kls, &null_ctl, never_see_null);
  3491   if (region != NULL) {
  3492     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
  3493     region->init_req(null_path, null_ctl);
  3494   } else {
  3495     assert(null_ctl == top(), "no loose ends");
  3497   return kls;
  3500 //--------------------(inline_native_Class_query helpers)---------------------
  3501 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
  3502 // Fall through if (mods & mask) == bits, take the guard otherwise.
  3503 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
  3504   // Branch around if the given klass has the given modifier bit set.
  3505   // Like generate_guard, adds a new path onto the region.
  3506   Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
  3507   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
  3508   Node* mask = intcon(modifier_mask);
  3509   Node* bits = intcon(modifier_bits);
  3510   Node* mbit = _gvn.transform(new (C) AndINode(mods, mask));
  3511   Node* cmp  = _gvn.transform(new (C) CmpINode(mbit, bits));
  3512   Node* bol  = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne));
  3513   return generate_fair_guard(bol, region);
  3515 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
  3516   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
  3519 //-------------------------inline_native_Class_query-------------------
  3520 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
  3521   const Type* return_type = TypeInt::BOOL;
  3522   Node* prim_return_value = top();  // what happens if it's a primitive class?
  3523   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3524   bool expect_prim = false;     // most of these guys expect to work on refs
  3526   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
  3528   Node* mirror = argument(0);
  3529   Node* obj    = top();
  3531   switch (id) {
  3532   case vmIntrinsics::_isInstance:
  3533     // nothing is an instance of a primitive type
  3534     prim_return_value = intcon(0);
  3535     obj = argument(1);
  3536     break;
  3537   case vmIntrinsics::_getModifiers:
  3538     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  3539     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
  3540     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
  3541     break;
  3542   case vmIntrinsics::_isInterface:
  3543     prim_return_value = intcon(0);
  3544     break;
  3545   case vmIntrinsics::_isArray:
  3546     prim_return_value = intcon(0);
  3547     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
  3548     break;
  3549   case vmIntrinsics::_isPrimitive:
  3550     prim_return_value = intcon(1);
  3551     expect_prim = true;  // obviously
  3552     break;
  3553   case vmIntrinsics::_getSuperclass:
  3554     prim_return_value = null();
  3555     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  3556     break;
  3557   case vmIntrinsics::_getComponentType:
  3558     prim_return_value = null();
  3559     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  3560     break;
  3561   case vmIntrinsics::_getClassAccessFlags:
  3562     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  3563     return_type = TypeInt::INT;  // not bool!  6297094
  3564     break;
  3565   default:
  3566     fatal_unexpected_iid(id);
  3567     break;
  3570   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
  3571   if (mirror_con == NULL)  return false;  // cannot happen?
  3573 #ifndef PRODUCT
  3574   if (C->print_intrinsics() || C->print_inlining()) {
  3575     ciType* k = mirror_con->java_mirror_type();
  3576     if (k) {
  3577       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
  3578       k->print_name();
  3579       tty->cr();
  3582 #endif
  3584   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
  3585   RegionNode* region = new (C) RegionNode(PATH_LIMIT);
  3586   record_for_igvn(region);
  3587   PhiNode* phi = new (C) PhiNode(region, return_type);
  3589   // The mirror will never be null of Reflection.getClassAccessFlags, however
  3590   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
  3591   // if it is. See bug 4774291.
  3593   // For Reflection.getClassAccessFlags(), the null check occurs in
  3594   // the wrong place; see inline_unsafe_access(), above, for a similar
  3595   // situation.
  3596   mirror = null_check(mirror);
  3597   // If mirror or obj is dead, only null-path is taken.
  3598   if (stopped())  return true;
  3600   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
  3602   // Now load the mirror's klass metaobject, and null-check it.
  3603   // Side-effects region with the control path if the klass is null.
  3604   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
  3605   // If kls is null, we have a primitive mirror.
  3606   phi->init_req(_prim_path, prim_return_value);
  3607   if (stopped()) { set_result(region, phi); return true; }
  3608   bool safe_for_replace = (region->in(_prim_path) == top());
  3610   Node* p;  // handy temp
  3611   Node* null_ctl;
  3613   // Now that we have the non-null klass, we can perform the real query.
  3614   // For constant classes, the query will constant-fold in LoadNode::Value.
  3615   Node* query_value = top();
  3616   switch (id) {
  3617   case vmIntrinsics::_isInstance:
  3618     // nothing is an instance of a primitive type
  3619     query_value = gen_instanceof(obj, kls, safe_for_replace);
  3620     break;
  3622   case vmIntrinsics::_getModifiers:
  3623     p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
  3624     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
  3625     break;
  3627   case vmIntrinsics::_isInterface:
  3628     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  3629     if (generate_interface_guard(kls, region) != NULL)
  3630       // A guard was added.  If the guard is taken, it was an interface.
  3631       phi->add_req(intcon(1));
  3632     // If we fall through, it's a plain class.
  3633     query_value = intcon(0);
  3634     break;
  3636   case vmIntrinsics::_isArray:
  3637     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
  3638     if (generate_array_guard(kls, region) != NULL)
  3639       // A guard was added.  If the guard is taken, it was an array.
  3640       phi->add_req(intcon(1));
  3641     // If we fall through, it's a plain class.
  3642     query_value = intcon(0);
  3643     break;
  3645   case vmIntrinsics::_isPrimitive:
  3646     query_value = intcon(0); // "normal" path produces false
  3647     break;
  3649   case vmIntrinsics::_getSuperclass:
  3650     // The rules here are somewhat unfortunate, but we can still do better
  3651     // with random logic than with a JNI call.
  3652     // Interfaces store null or Object as _super, but must report null.
  3653     // Arrays store an intermediate super as _super, but must report Object.
  3654     // Other types can report the actual _super.
  3655     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  3656     if (generate_interface_guard(kls, region) != NULL)
  3657       // A guard was added.  If the guard is taken, it was an interface.
  3658       phi->add_req(null());
  3659     if (generate_array_guard(kls, region) != NULL)
  3660       // A guard was added.  If the guard is taken, it was an array.
  3661       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
  3662     // If we fall through, it's a plain class.  Get its _super.
  3663     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
  3664     kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
  3665     null_ctl = top();
  3666     kls = null_check_oop(kls, &null_ctl);
  3667     if (null_ctl != top()) {
  3668       // If the guard is taken, Object.superClass is null (both klass and mirror).
  3669       region->add_req(null_ctl);
  3670       phi   ->add_req(null());
  3672     if (!stopped()) {
  3673       query_value = load_mirror_from_klass(kls);
  3675     break;
  3677   case vmIntrinsics::_getComponentType:
  3678     if (generate_array_guard(kls, region) != NULL) {
  3679       // Be sure to pin the oop load to the guard edge just created:
  3680       Node* is_array_ctrl = region->in(region->req()-1);
  3681       Node* cma = basic_plus_adr(kls, in_bytes(ArrayKlass::component_mirror_offset()));
  3682       Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT, MemNode::unordered);
  3683       phi->add_req(cmo);
  3685     query_value = null();  // non-array case is null
  3686     break;
  3688   case vmIntrinsics::_getClassAccessFlags:
  3689     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
  3690     query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
  3691     break;
  3693   default:
  3694     fatal_unexpected_iid(id);
  3695     break;
  3698   // Fall-through is the normal case of a query to a real class.
  3699   phi->init_req(1, query_value);
  3700   region->init_req(1, control());
  3702   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3703   set_result(region, phi);
  3704   return true;
  3707 //--------------------------inline_native_subtype_check------------------------
  3708 // This intrinsic takes the JNI calls out of the heart of
  3709 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
  3710 bool LibraryCallKit::inline_native_subtype_check() {
  3711   // Pull both arguments off the stack.
  3712   Node* args[2];                // two java.lang.Class mirrors: superc, subc
  3713   args[0] = argument(0);
  3714   args[1] = argument(1);
  3715   Node* klasses[2];             // corresponding Klasses: superk, subk
  3716   klasses[0] = klasses[1] = top();
  3718   enum {
  3719     // A full decision tree on {superc is prim, subc is prim}:
  3720     _prim_0_path = 1,           // {P,N} => false
  3721                                 // {P,P} & superc!=subc => false
  3722     _prim_same_path,            // {P,P} & superc==subc => true
  3723     _prim_1_path,               // {N,P} => false
  3724     _ref_subtype_path,          // {N,N} & subtype check wins => true
  3725     _both_ref_path,             // {N,N} & subtype check loses => false
  3726     PATH_LIMIT
  3727   };
  3729   RegionNode* region = new (C) RegionNode(PATH_LIMIT);
  3730   Node*       phi    = new (C) PhiNode(region, TypeInt::BOOL);
  3731   record_for_igvn(region);
  3733   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
  3734   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  3735   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
  3737   // First null-check both mirrors and load each mirror's klass metaobject.
  3738   int which_arg;
  3739   for (which_arg = 0; which_arg <= 1; which_arg++) {
  3740     Node* arg = args[which_arg];
  3741     arg = null_check(arg);
  3742     if (stopped())  break;
  3743     args[which_arg] = arg;
  3745     Node* p = basic_plus_adr(arg, class_klass_offset);
  3746     Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
  3747     klasses[which_arg] = _gvn.transform(kls);
  3750   // Having loaded both klasses, test each for null.
  3751   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3752   for (which_arg = 0; which_arg <= 1; which_arg++) {
  3753     Node* kls = klasses[which_arg];
  3754     Node* null_ctl = top();
  3755     kls = null_check_oop(kls, &null_ctl, never_see_null);
  3756     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
  3757     region->init_req(prim_path, null_ctl);
  3758     if (stopped())  break;
  3759     klasses[which_arg] = kls;
  3762   if (!stopped()) {
  3763     // now we have two reference types, in klasses[0..1]
  3764     Node* subk   = klasses[1];  // the argument to isAssignableFrom
  3765     Node* superk = klasses[0];  // the receiver
  3766     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
  3767     // now we have a successful reference subtype check
  3768     region->set_req(_ref_subtype_path, control());
  3771   // If both operands are primitive (both klasses null), then
  3772   // we must return true when they are identical primitives.
  3773   // It is convenient to test this after the first null klass check.
  3774   set_control(region->in(_prim_0_path)); // go back to first null check
  3775   if (!stopped()) {
  3776     // Since superc is primitive, make a guard for the superc==subc case.
  3777     Node* cmp_eq = _gvn.transform(new (C) CmpPNode(args[0], args[1]));
  3778     Node* bol_eq = _gvn.transform(new (C) BoolNode(cmp_eq, BoolTest::eq));
  3779     generate_guard(bol_eq, region, PROB_FAIR);
  3780     if (region->req() == PATH_LIMIT+1) {
  3781       // A guard was added.  If the added guard is taken, superc==subc.
  3782       region->swap_edges(PATH_LIMIT, _prim_same_path);
  3783       region->del_req(PATH_LIMIT);
  3785     region->set_req(_prim_0_path, control()); // Not equal after all.
  3788   // these are the only paths that produce 'true':
  3789   phi->set_req(_prim_same_path,   intcon(1));
  3790   phi->set_req(_ref_subtype_path, intcon(1));
  3792   // pull together the cases:
  3793   assert(region->req() == PATH_LIMIT, "sane region");
  3794   for (uint i = 1; i < region->req(); i++) {
  3795     Node* ctl = region->in(i);
  3796     if (ctl == NULL || ctl == top()) {
  3797       region->set_req(i, top());
  3798       phi   ->set_req(i, top());
  3799     } else if (phi->in(i) == NULL) {
  3800       phi->set_req(i, intcon(0)); // all other paths produce 'false'
  3804   set_control(_gvn.transform(region));
  3805   set_result(_gvn.transform(phi));
  3806   return true;
  3809 //---------------------generate_array_guard_common------------------------
  3810 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
  3811                                                   bool obj_array, bool not_array) {
  3812   // If obj_array/non_array==false/false:
  3813   // Branch around if the given klass is in fact an array (either obj or prim).
  3814   // If obj_array/non_array==false/true:
  3815   // Branch around if the given klass is not an array klass of any kind.
  3816   // If obj_array/non_array==true/true:
  3817   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
  3818   // If obj_array/non_array==true/false:
  3819   // Branch around if the kls is an oop array (Object[] or subtype)
  3820   //
  3821   // Like generate_guard, adds a new path onto the region.
  3822   jint  layout_con = 0;
  3823   Node* layout_val = get_layout_helper(kls, layout_con);
  3824   if (layout_val == NULL) {
  3825     bool query = (obj_array
  3826                   ? Klass::layout_helper_is_objArray(layout_con)
  3827                   : Klass::layout_helper_is_array(layout_con));
  3828     if (query == not_array) {
  3829       return NULL;                       // never a branch
  3830     } else {                             // always a branch
  3831       Node* always_branch = control();
  3832       if (region != NULL)
  3833         region->add_req(always_branch);
  3834       set_control(top());
  3835       return always_branch;
  3838   // Now test the correct condition.
  3839   jint  nval = (obj_array
  3840                 ? (jint)(Klass::_lh_array_tag_type_value
  3841                    <<    Klass::_lh_array_tag_shift)
  3842                 : Klass::_lh_neutral_value);
  3843   Node* cmp = _gvn.transform(new(C) CmpINode(layout_val, intcon(nval)));
  3844   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
  3845   // invert the test if we are looking for a non-array
  3846   if (not_array)  btest = BoolTest(btest).negate();
  3847   Node* bol = _gvn.transform(new(C) BoolNode(cmp, btest));
  3848   return generate_fair_guard(bol, region);
  3852 //-----------------------inline_native_newArray--------------------------
  3853 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
  3854 bool LibraryCallKit::inline_native_newArray() {
  3855   Node* mirror    = argument(0);
  3856   Node* count_val = argument(1);
  3858   mirror = null_check(mirror);
  3859   // If mirror or obj is dead, only null-path is taken.
  3860   if (stopped())  return true;
  3862   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
  3863   RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
  3864   PhiNode*    result_val = new(C) PhiNode(result_reg,
  3865                                           TypeInstPtr::NOTNULL);
  3866   PhiNode*    result_io  = new(C) PhiNode(result_reg, Type::ABIO);
  3867   PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY,
  3868                                           TypePtr::BOTTOM);
  3870   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3871   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
  3872                                                   result_reg, _slow_path);
  3873   Node* normal_ctl   = control();
  3874   Node* no_array_ctl = result_reg->in(_slow_path);
  3876   // Generate code for the slow case.  We make a call to newArray().
  3877   set_control(no_array_ctl);
  3878   if (!stopped()) {
  3879     // Either the input type is void.class, or else the
  3880     // array klass has not yet been cached.  Either the
  3881     // ensuing call will throw an exception, or else it
  3882     // will cache the array klass for next time.
  3883     PreserveJVMState pjvms(this);
  3884     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
  3885     Node* slow_result = set_results_for_java_call(slow_call);
  3886     // this->control() comes from set_results_for_java_call
  3887     result_reg->set_req(_slow_path, control());
  3888     result_val->set_req(_slow_path, slow_result);
  3889     result_io ->set_req(_slow_path, i_o());
  3890     result_mem->set_req(_slow_path, reset_memory());
  3893   set_control(normal_ctl);
  3894   if (!stopped()) {
  3895     // Normal case:  The array type has been cached in the java.lang.Class.
  3896     // The following call works fine even if the array type is polymorphic.
  3897     // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3898     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
  3899     result_reg->init_req(_normal_path, control());
  3900     result_val->init_req(_normal_path, obj);
  3901     result_io ->init_req(_normal_path, i_o());
  3902     result_mem->init_req(_normal_path, reset_memory());
  3905   // Return the combined state.
  3906   set_i_o(        _gvn.transform(result_io)  );
  3907   set_all_memory( _gvn.transform(result_mem));
  3909   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3910   set_result(result_reg, result_val);
  3911   return true;
  3914 //----------------------inline_native_getLength--------------------------
  3915 // public static native int java.lang.reflect.Array.getLength(Object array);
  3916 bool LibraryCallKit::inline_native_getLength() {
  3917   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3919   Node* array = null_check(argument(0));
  3920   // If array is dead, only null-path is taken.
  3921   if (stopped())  return true;
  3923   // Deoptimize if it is a non-array.
  3924   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
  3926   if (non_array != NULL) {
  3927     PreserveJVMState pjvms(this);
  3928     set_control(non_array);
  3929     uncommon_trap(Deoptimization::Reason_intrinsic,
  3930                   Deoptimization::Action_maybe_recompile);
  3933   // If control is dead, only non-array-path is taken.
  3934   if (stopped())  return true;
  3936   // The works fine even if the array type is polymorphic.
  3937   // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3938   Node* result = load_array_length(array);
  3940   C->set_has_split_ifs(true);  // Has chance for split-if optimization
  3941   set_result(result);
  3942   return true;
  3945 //------------------------inline_array_copyOf----------------------------
  3946 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
  3947 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
  3948 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
  3949   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3951   // Get the arguments.
  3952   Node* original          = argument(0);
  3953   Node* start             = is_copyOfRange? argument(1): intcon(0);
  3954   Node* end               = is_copyOfRange? argument(2): argument(1);
  3955   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
  3957   Node* newcopy = NULL;
  3959   // Set the original stack and the reexecute bit for the interpreter to reexecute
  3960   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
  3961   { PreserveReexecuteState preexecs(this);
  3962     jvms()->set_should_reexecute(true);
  3964     array_type_mirror = null_check(array_type_mirror);
  3965     original          = null_check(original);
  3967     // Check if a null path was taken unconditionally.
  3968     if (stopped())  return true;
  3970     Node* orig_length = load_array_length(original);
  3972     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
  3973     klass_node = null_check(klass_node);
  3975     RegionNode* bailout = new (C) RegionNode(1);
  3976     record_for_igvn(bailout);
  3978     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
  3979     // Bail out if that is so.
  3980     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
  3981     if (not_objArray != NULL) {
  3982       // Improve the klass node's type from the new optimistic assumption:
  3983       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
  3984       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  3985       Node* cast = new (C) CastPPNode(klass_node, akls);
  3986       cast->init_req(0, control());
  3987       klass_node = _gvn.transform(cast);
  3990     // Bail out if either start or end is negative.
  3991     generate_negative_guard(start, bailout, &start);
  3992     generate_negative_guard(end,   bailout, &end);
  3994     Node* length = end;
  3995     if (_gvn.type(start) != TypeInt::ZERO) {
  3996       length = _gvn.transform(new (C) SubINode(end, start));
  3999     // Bail out if length is negative.
  4000     // Without this the new_array would throw
  4001     // NegativeArraySizeException but IllegalArgumentException is what
  4002     // should be thrown
  4003     generate_negative_guard(length, bailout, &length);
  4005     if (bailout->req() > 1) {
  4006       PreserveJVMState pjvms(this);
  4007       set_control(_gvn.transform(bailout));
  4008       uncommon_trap(Deoptimization::Reason_intrinsic,
  4009                     Deoptimization::Action_maybe_recompile);
  4012     if (!stopped()) {
  4013       // How many elements will we copy from the original?
  4014       // The answer is MinI(orig_length - start, length).
  4015       Node* orig_tail = _gvn.transform(new (C) SubINode(orig_length, start));
  4016       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
  4018       newcopy = new_array(klass_node, length, 0);  // no argments to push
  4020       // Generate a direct call to the right arraycopy function(s).
  4021       // We know the copy is disjoint but we might not know if the
  4022       // oop stores need checking.
  4023       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
  4024       // This will fail a store-check if x contains any non-nulls.
  4025       bool disjoint_bases = true;
  4026       // if start > orig_length then the length of the copy may be
  4027       // negative.
  4028       bool length_never_negative = !is_copyOfRange;
  4029       generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  4030                          original, start, newcopy, intcon(0), moved,
  4031                          disjoint_bases, length_never_negative);
  4033   } // original reexecute is set back here
  4035   C->set_has_split_ifs(true); // Has chance for split-if optimization
  4036   if (!stopped()) {
  4037     set_result(newcopy);
  4039   return true;
  4043 //----------------------generate_virtual_guard---------------------------
  4044 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
  4045 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
  4046                                              RegionNode* slow_region) {
  4047   ciMethod* method = callee();
  4048   int vtable_index = method->vtable_index();
  4049   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
  4050          err_msg_res("bad index %d", vtable_index));
  4051   // Get the Method* out of the appropriate vtable entry.
  4052   int entry_offset  = (InstanceKlass::vtable_start_offset() +
  4053                      vtable_index*vtableEntry::size()) * wordSize +
  4054                      vtableEntry::method_offset_in_bytes();
  4055   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
  4056   Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
  4058   // Compare the target method with the expected method (e.g., Object.hashCode).
  4059   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
  4061   Node* native_call = makecon(native_call_addr);
  4062   Node* chk_native  = _gvn.transform(new(C) CmpPNode(target_call, native_call));
  4063   Node* test_native = _gvn.transform(new(C) BoolNode(chk_native, BoolTest::ne));
  4065   return generate_slow_guard(test_native, slow_region);
  4068 //-----------------------generate_method_call----------------------------
  4069 // Use generate_method_call to make a slow-call to the real
  4070 // method if the fast path fails.  An alternative would be to
  4071 // use a stub like OptoRuntime::slow_arraycopy_Java.
  4072 // This only works for expanding the current library call,
  4073 // not another intrinsic.  (E.g., don't use this for making an
  4074 // arraycopy call inside of the copyOf intrinsic.)
  4075 CallJavaNode*
  4076 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
  4077   // When compiling the intrinsic method itself, do not use this technique.
  4078   guarantee(callee() != C->method(), "cannot make slow-call to self");
  4080   ciMethod* method = callee();
  4081   // ensure the JVMS we have will be correct for this call
  4082   guarantee(method_id == method->intrinsic_id(), "must match");
  4084   const TypeFunc* tf = TypeFunc::make(method);
  4085   CallJavaNode* slow_call;
  4086   if (is_static) {
  4087     assert(!is_virtual, "");
  4088     slow_call = new(C) CallStaticJavaNode(C, tf,
  4089                            SharedRuntime::get_resolve_static_call_stub(),
  4090                            method, bci());
  4091   } else if (is_virtual) {
  4092     null_check_receiver();
  4093     int vtable_index = Method::invalid_vtable_index;
  4094     if (UseInlineCaches) {
  4095       // Suppress the vtable call
  4096     } else {
  4097       // hashCode and clone are not a miranda methods,
  4098       // so the vtable index is fixed.
  4099       // No need to use the linkResolver to get it.
  4100        vtable_index = method->vtable_index();
  4101        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
  4102               err_msg_res("bad index %d", vtable_index));
  4104     slow_call = new(C) CallDynamicJavaNode(tf,
  4105                           SharedRuntime::get_resolve_virtual_call_stub(),
  4106                           method, vtable_index, bci());
  4107   } else {  // neither virtual nor static:  opt_virtual
  4108     null_check_receiver();
  4109     slow_call = new(C) CallStaticJavaNode(C, tf,
  4110                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
  4111                                 method, bci());
  4112     slow_call->set_optimized_virtual(true);
  4114   set_arguments_for_java_call(slow_call);
  4115   set_edges_for_java_call(slow_call);
  4116   return slow_call;
  4120 /**
  4121  * Build special case code for calls to hashCode on an object. This call may
  4122  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
  4123  * slightly different code.
  4124  */
  4125 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
  4126   assert(is_static == callee()->is_static(), "correct intrinsic selection");
  4127   assert(!(is_virtual && is_static), "either virtual, special, or static");
  4129   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
  4131   RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
  4132   PhiNode*    result_val = new(C) PhiNode(result_reg, TypeInt::INT);
  4133   PhiNode*    result_io  = new(C) PhiNode(result_reg, Type::ABIO);
  4134   PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
  4135   Node* obj = NULL;
  4136   if (!is_static) {
  4137     // Check for hashing null object
  4138     obj = null_check_receiver();
  4139     if (stopped())  return true;        // unconditionally null
  4140     result_reg->init_req(_null_path, top());
  4141     result_val->init_req(_null_path, top());
  4142   } else {
  4143     // Do a null check, and return zero if null.
  4144     // System.identityHashCode(null) == 0
  4145     obj = argument(0);
  4146     Node* null_ctl = top();
  4147     obj = null_check_oop(obj, &null_ctl);
  4148     result_reg->init_req(_null_path, null_ctl);
  4149     result_val->init_req(_null_path, _gvn.intcon(0));
  4152   // Unconditionally null?  Then return right away.
  4153   if (stopped()) {
  4154     set_control( result_reg->in(_null_path));
  4155     if (!stopped())
  4156       set_result(result_val->in(_null_path));
  4157     return true;
  4160   // We only go to the fast case code if we pass a number of guards.  The
  4161   // paths which do not pass are accumulated in the slow_region.
  4162   RegionNode* slow_region = new (C) RegionNode(1);
  4163   record_for_igvn(slow_region);
  4165   // If this is a virtual call, we generate a funny guard.  We pull out
  4166   // the vtable entry corresponding to hashCode() from the target object.
  4167   // If the target method which we are calling happens to be the native
  4168   // Object hashCode() method, we pass the guard.  We do not need this
  4169   // guard for non-virtual calls -- the caller is known to be the native
  4170   // Object hashCode().
  4171   if (is_virtual) {
  4172     // After null check, get the object's klass.
  4173     Node* obj_klass = load_object_klass(obj);
  4174     generate_virtual_guard(obj_klass, slow_region);
  4177   // Get the header out of the object, use LoadMarkNode when available
  4178   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
  4179   // The control of the load must be NULL. Otherwise, the load can move before
  4180   // the null check after castPP removal.
  4181   Node* no_ctrl = NULL;
  4182   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
  4184   // Test the header to see if it is unlocked.
  4185   Node* lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
  4186   Node* lmasked_header = _gvn.transform(new (C) AndXNode(header, lock_mask));
  4187   Node* unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
  4188   Node* chk_unlocked   = _gvn.transform(new (C) CmpXNode( lmasked_header, unlocked_val));
  4189   Node* test_unlocked  = _gvn.transform(new (C) BoolNode( chk_unlocked, BoolTest::ne));
  4191   generate_slow_guard(test_unlocked, slow_region);
  4193   // Get the hash value and check to see that it has been properly assigned.
  4194   // We depend on hash_mask being at most 32 bits and avoid the use of
  4195   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
  4196   // vm: see markOop.hpp.
  4197   Node* hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
  4198   Node* hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
  4199   Node* hshifted_header= _gvn.transform(new (C) URShiftXNode(header, hash_shift));
  4200   // This hack lets the hash bits live anywhere in the mark object now, as long
  4201   // as the shift drops the relevant bits into the low 32 bits.  Note that
  4202   // Java spec says that HashCode is an int so there's no point in capturing
  4203   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
  4204   hshifted_header      = ConvX2I(hshifted_header);
  4205   Node* hash_val       = _gvn.transform(new (C) AndINode(hshifted_header, hash_mask));
  4207   Node* no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
  4208   Node* chk_assigned   = _gvn.transform(new (C) CmpINode( hash_val, no_hash_val));
  4209   Node* test_assigned  = _gvn.transform(new (C) BoolNode( chk_assigned, BoolTest::eq));
  4211   generate_slow_guard(test_assigned, slow_region);
  4213   Node* init_mem = reset_memory();
  4214   // fill in the rest of the null path:
  4215   result_io ->init_req(_null_path, i_o());
  4216   result_mem->init_req(_null_path, init_mem);
  4218   result_val->init_req(_fast_path, hash_val);
  4219   result_reg->init_req(_fast_path, control());
  4220   result_io ->init_req(_fast_path, i_o());
  4221   result_mem->init_req(_fast_path, init_mem);
  4223   // Generate code for the slow case.  We make a call to hashCode().
  4224   set_control(_gvn.transform(slow_region));
  4225   if (!stopped()) {
  4226     // No need for PreserveJVMState, because we're using up the present state.
  4227     set_all_memory(init_mem);
  4228     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
  4229     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
  4230     Node* slow_result = set_results_for_java_call(slow_call);
  4231     // this->control() comes from set_results_for_java_call
  4232     result_reg->init_req(_slow_path, control());
  4233     result_val->init_req(_slow_path, slow_result);
  4234     result_io  ->set_req(_slow_path, i_o());
  4235     result_mem ->set_req(_slow_path, reset_memory());
  4238   // Return the combined state.
  4239   set_i_o(        _gvn.transform(result_io)  );
  4240   set_all_memory( _gvn.transform(result_mem));
  4242   set_result(result_reg, result_val);
  4243   return true;
  4246 //---------------------------inline_native_getClass----------------------------
  4247 // public final native Class<?> java.lang.Object.getClass();
  4248 //
  4249 // Build special case code for calls to getClass on an object.
  4250 bool LibraryCallKit::inline_native_getClass() {
  4251   Node* obj = null_check_receiver();
  4252   if (stopped())  return true;
  4253   set_result(load_mirror_from_klass(load_object_klass(obj)));
  4254   return true;
  4257 //-----------------inline_native_Reflection_getCallerClass---------------------
  4258 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
  4259 //
  4260 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
  4261 //
  4262 // NOTE: This code must perform the same logic as JVM_GetCallerClass
  4263 // in that it must skip particular security frames and checks for
  4264 // caller sensitive methods.
  4265 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
  4266 #ifndef PRODUCT
  4267   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  4268     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
  4270 #endif
  4272   if (!jvms()->has_method()) {
  4273 #ifndef PRODUCT
  4274     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  4275       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
  4277 #endif
  4278     return false;
  4281   // Walk back up the JVM state to find the caller at the required
  4282   // depth.
  4283   JVMState* caller_jvms = jvms();
  4285   // Cf. JVM_GetCallerClass
  4286   // NOTE: Start the loop at depth 1 because the current JVM state does
  4287   // not include the Reflection.getCallerClass() frame.
  4288   for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
  4289     ciMethod* m = caller_jvms->method();
  4290     switch (n) {
  4291     case 0:
  4292       fatal("current JVM state does not include the Reflection.getCallerClass frame");
  4293       break;
  4294     case 1:
  4295       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
  4296       if (!m->caller_sensitive()) {
  4297 #ifndef PRODUCT
  4298         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  4299           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
  4301 #endif
  4302         return false;  // bail-out; let JVM_GetCallerClass do the work
  4304       break;
  4305     default:
  4306       if (!m->is_ignored_by_security_stack_walk()) {
  4307         // We have reached the desired frame; return the holder class.
  4308         // Acquire method holder as java.lang.Class and push as constant.
  4309         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
  4310         ciInstance* caller_mirror = caller_klass->java_mirror();
  4311         set_result(makecon(TypeInstPtr::make(caller_mirror)));
  4313 #ifndef PRODUCT
  4314         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  4315           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());
  4316           tty->print_cr("  JVM state at this point:");
  4317           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
  4318             ciMethod* m = jvms()->of_depth(i)->method();
  4319             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
  4322 #endif
  4323         return true;
  4325       break;
  4329 #ifndef PRODUCT
  4330   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
  4331     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
  4332     tty->print_cr("  JVM state at this point:");
  4333     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
  4334       ciMethod* m = jvms()->of_depth(i)->method();
  4335       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
  4338 #endif
  4340   return false;  // bail-out; let JVM_GetCallerClass do the work
  4343 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
  4344   Node* arg = argument(0);
  4345   Node* result = NULL;
  4347   switch (id) {
  4348   case vmIntrinsics::_floatToRawIntBits:    result = new (C) MoveF2INode(arg);  break;
  4349   case vmIntrinsics::_intBitsToFloat:       result = new (C) MoveI2FNode(arg);  break;
  4350   case vmIntrinsics::_doubleToRawLongBits:  result = new (C) MoveD2LNode(arg);  break;
  4351   case vmIntrinsics::_longBitsToDouble:     result = new (C) MoveL2DNode(arg);  break;
  4353   case vmIntrinsics::_doubleToLongBits: {
  4354     // two paths (plus control) merge in a wood
  4355     RegionNode *r = new (C) RegionNode(3);
  4356     Node *phi = new (C) PhiNode(r, TypeLong::LONG);
  4358     Node *cmpisnan = _gvn.transform(new (C) CmpDNode(arg, arg));
  4359     // Build the boolean node
  4360     Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));
  4362     // Branch either way.
  4363     // NaN case is less traveled, which makes all the difference.
  4364     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  4365     Node *opt_isnan = _gvn.transform(ifisnan);
  4366     assert( opt_isnan->is_If(), "Expect an IfNode");
  4367     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  4368     Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));
  4370     set_control(iftrue);
  4372     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  4373     Node *slow_result = longcon(nan_bits); // return NaN
  4374     phi->init_req(1, _gvn.transform( slow_result ));
  4375     r->init_req(1, iftrue);
  4377     // Else fall through
  4378     Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));
  4379     set_control(iffalse);
  4381     phi->init_req(2, _gvn.transform(new (C) MoveD2LNode(arg)));
  4382     r->init_req(2, iffalse);
  4384     // Post merge
  4385     set_control(_gvn.transform(r));
  4386     record_for_igvn(r);
  4388     C->set_has_split_ifs(true); // Has chance for split-if optimization
  4389     result = phi;
  4390     assert(result->bottom_type()->isa_long(), "must be");
  4391     break;
  4394   case vmIntrinsics::_floatToIntBits: {
  4395     // two paths (plus control) merge in a wood
  4396     RegionNode *r = new (C) RegionNode(3);
  4397     Node *phi = new (C) PhiNode(r, TypeInt::INT);
  4399     Node *cmpisnan = _gvn.transform(new (C) CmpFNode(arg, arg));
  4400     // Build the boolean node
  4401     Node *bolisnan = _gvn.transform(new (C) BoolNode(cmpisnan, BoolTest::ne));
  4403     // Branch either way.
  4404     // NaN case is less traveled, which makes all the difference.
  4405     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  4406     Node *opt_isnan = _gvn.transform(ifisnan);
  4407     assert( opt_isnan->is_If(), "Expect an IfNode");
  4408     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  4409     Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan));
  4411     set_control(iftrue);
  4413     static const jint nan_bits = 0x7fc00000;
  4414     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
  4415     phi->init_req(1, _gvn.transform( slow_result ));
  4416     r->init_req(1, iftrue);
  4418     // Else fall through
  4419     Node *iffalse = _gvn.transform(new (C) IfFalseNode(opt_ifisnan));
  4420     set_control(iffalse);
  4422     phi->init_req(2, _gvn.transform(new (C) MoveF2INode(arg)));
  4423     r->init_req(2, iffalse);
  4425     // Post merge
  4426     set_control(_gvn.transform(r));
  4427     record_for_igvn(r);
  4429     C->set_has_split_ifs(true); // Has chance for split-if optimization
  4430     result = phi;
  4431     assert(result->bottom_type()->isa_int(), "must be");
  4432     break;
  4435   default:
  4436     fatal_unexpected_iid(id);
  4437     break;
  4439   set_result(_gvn.transform(result));
  4440   return true;
  4443 #ifdef _LP64
  4444 #define XTOP ,top() /*additional argument*/
  4445 #else  //_LP64
  4446 #define XTOP        /*no additional argument*/
  4447 #endif //_LP64
  4449 //----------------------inline_unsafe_copyMemory-------------------------
  4450 // public native void sun.misc.Unsafe.copyMemory(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
  4451 bool LibraryCallKit::inline_unsafe_copyMemory() {
  4452   if (callee()->is_static())  return false;  // caller must have the capability!
  4453   null_check_receiver();  // null-check receiver
  4454   if (stopped())  return true;
  4456   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  4458   Node* src_ptr =         argument(1);   // type: oop
  4459   Node* src_off = ConvL2X(argument(2));  // type: long
  4460   Node* dst_ptr =         argument(4);   // type: oop
  4461   Node* dst_off = ConvL2X(argument(5));  // type: long
  4462   Node* size    = ConvL2X(argument(7));  // type: long
  4464   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  4465          "fieldOffset must be byte-scaled");
  4467   Node* src = make_unsafe_address(src_ptr, src_off);
  4468   Node* dst = make_unsafe_address(dst_ptr, dst_off);
  4470   // Conservatively insert a memory barrier on all memory slices.
  4471   // Do not let writes of the copy source or destination float below the copy.
  4472   insert_mem_bar(Op_MemBarCPUOrder);
  4474   // Call it.  Note that the length argument is not scaled.
  4475   make_runtime_call(RC_LEAF|RC_NO_FP,
  4476                     OptoRuntime::fast_arraycopy_Type(),
  4477                     StubRoutines::unsafe_arraycopy(),
  4478                     "unsafe_arraycopy",
  4479                     TypeRawPtr::BOTTOM,
  4480                     src, dst, size XTOP);
  4482   // Do not let reads of the copy destination float above the copy.
  4483   insert_mem_bar(Op_MemBarCPUOrder);
  4485   return true;
  4488 //------------------------clone_coping-----------------------------------
  4489 // Helper function for inline_native_clone.
  4490 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
  4491   assert(obj_size != NULL, "");
  4492   Node* raw_obj = alloc_obj->in(1);
  4493   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
  4495   AllocateNode* alloc = NULL;
  4496   if (ReduceBulkZeroing) {
  4497     // We will be completely responsible for initializing this object -
  4498     // mark Initialize node as complete.
  4499     alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
  4500     // The object was just allocated - there should be no any stores!
  4501     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
  4502     // Mark as complete_with_arraycopy so that on AllocateNode
  4503     // expansion, we know this AllocateNode is initialized by an array
  4504     // copy and a StoreStore barrier exists after the array copy.
  4505     alloc->initialization()->set_complete_with_arraycopy();
  4508   // Copy the fastest available way.
  4509   // TODO: generate fields copies for small objects instead.
  4510   Node* src  = obj;
  4511   Node* dest = alloc_obj;
  4512   Node* size = _gvn.transform(obj_size);
  4514   // Exclude the header but include array length to copy by 8 bytes words.
  4515   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
  4516   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
  4517                             instanceOopDesc::base_offset_in_bytes();
  4518   // base_off:
  4519   // 8  - 32-bit VM
  4520   // 12 - 64-bit VM, compressed klass
  4521   // 16 - 64-bit VM, normal klass
  4522   if (base_off % BytesPerLong != 0) {
  4523     assert(UseCompressedClassPointers, "");
  4524     if (is_array) {
  4525       // Exclude length to copy by 8 bytes words.
  4526       base_off += sizeof(int);
  4527     } else {
  4528       // Include klass to copy by 8 bytes words.
  4529       base_off = instanceOopDesc::klass_offset_in_bytes();
  4531     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
  4533   src  = basic_plus_adr(src,  base_off);
  4534   dest = basic_plus_adr(dest, base_off);
  4536   // Compute the length also, if needed:
  4537   Node* countx = size;
  4538   countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(base_off)));
  4539   countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong) ));
  4541   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  4542   bool disjoint_bases = true;
  4543   generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,
  4544                                src, NULL, dest, NULL, countx,
  4545                                /*dest_uninitialized*/true);
  4547   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
  4548   if (card_mark) {
  4549     assert(!is_array, "");
  4550     // Put in store barrier for any and all oops we are sticking
  4551     // into this object.  (We could avoid this if we could prove
  4552     // that the object type contains no oop fields at all.)
  4553     Node* no_particular_value = NULL;
  4554     Node* no_particular_field = NULL;
  4555     int raw_adr_idx = Compile::AliasIdxRaw;
  4556     post_barrier(control(),
  4557                  memory(raw_adr_type),
  4558                  alloc_obj,
  4559                  no_particular_field,
  4560                  raw_adr_idx,
  4561                  no_particular_value,
  4562                  T_OBJECT,
  4563                  false);
  4566   // Do not let reads from the cloned object float above the arraycopy.
  4567   if (alloc != NULL) {
  4568     // Do not let stores that initialize this object be reordered with
  4569     // a subsequent store that would make this object accessible by
  4570     // other threads.
  4571     // Record what AllocateNode this StoreStore protects so that
  4572     // escape analysis can go from the MemBarStoreStoreNode to the
  4573     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
  4574     // based on the escape status of the AllocateNode.
  4575     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
  4576   } else {
  4577     insert_mem_bar(Op_MemBarCPUOrder);
  4581 //------------------------inline_native_clone----------------------------
  4582 // protected native Object java.lang.Object.clone();
  4583 //
  4584 // Here are the simple edge cases:
  4585 //  null receiver => normal trap
  4586 //  virtual and clone was overridden => slow path to out-of-line clone
  4587 //  not cloneable or finalizer => slow path to out-of-line Object.clone
  4588 //
  4589 // The general case has two steps, allocation and copying.
  4590 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
  4591 //
  4592 // Copying also has two cases, oop arrays and everything else.
  4593 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
  4594 // Everything else uses the tight inline loop supplied by CopyArrayNode.
  4595 //
  4596 // These steps fold up nicely if and when the cloned object's klass
  4597 // can be sharply typed as an object array, a type array, or an instance.
  4598 //
  4599 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
  4600   PhiNode* result_val;
  4602   // Set the reexecute bit for the interpreter to reexecute
  4603   // the bytecode that invokes Object.clone if deoptimization happens.
  4604   { PreserveReexecuteState preexecs(this);
  4605     jvms()->set_should_reexecute(true);
  4607     Node* obj = null_check_receiver();
  4608     if (stopped())  return true;
  4610     Node* obj_klass = load_object_klass(obj);
  4611     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
  4612     const TypeOopPtr*   toop   = ((tklass != NULL)
  4613                                 ? tklass->as_instance_type()
  4614                                 : TypeInstPtr::NOTNULL);
  4616     // Conservatively insert a memory barrier on all memory slices.
  4617     // Do not let writes into the original float below the clone.
  4618     insert_mem_bar(Op_MemBarCPUOrder);
  4620     // paths into result_reg:
  4621     enum {
  4622       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
  4623       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
  4624       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
  4625       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
  4626       PATH_LIMIT
  4627     };
  4628     RegionNode* result_reg = new(C) RegionNode(PATH_LIMIT);
  4629     result_val             = new(C) PhiNode(result_reg,
  4630                                             TypeInstPtr::NOTNULL);
  4631     PhiNode*    result_i_o = new(C) PhiNode(result_reg, Type::ABIO);
  4632     PhiNode*    result_mem = new(C) PhiNode(result_reg, Type::MEMORY,
  4633                                             TypePtr::BOTTOM);
  4634     record_for_igvn(result_reg);
  4636     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  4637     int raw_adr_idx = Compile::AliasIdxRaw;
  4639     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
  4640     if (array_ctl != NULL) {
  4641       // It's an array.
  4642       PreserveJVMState pjvms(this);
  4643       set_control(array_ctl);
  4644       Node* obj_length = load_array_length(obj);
  4645       Node* obj_size  = NULL;
  4646       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size);  // no arguments to push
  4648       if (!use_ReduceInitialCardMarks()) {
  4649         // If it is an oop array, it requires very special treatment,
  4650         // because card marking is required on each card of the array.
  4651         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
  4652         if (is_obja != NULL) {
  4653           PreserveJVMState pjvms2(this);
  4654           set_control(is_obja);
  4655           // Generate a direct call to the right arraycopy function(s).
  4656           bool disjoint_bases = true;
  4657           bool length_never_negative = true;
  4658           generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  4659                              obj, intcon(0), alloc_obj, intcon(0),
  4660                              obj_length,
  4661                              disjoint_bases, length_never_negative);
  4662           result_reg->init_req(_objArray_path, control());
  4663           result_val->init_req(_objArray_path, alloc_obj);
  4664           result_i_o ->set_req(_objArray_path, i_o());
  4665           result_mem ->set_req(_objArray_path, reset_memory());
  4668       // Otherwise, there are no card marks to worry about.
  4669       // (We can dispense with card marks if we know the allocation
  4670       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
  4671       //  causes the non-eden paths to take compensating steps to
  4672       //  simulate a fresh allocation, so that no further
  4673       //  card marks are required in compiled code to initialize
  4674       //  the object.)
  4676       if (!stopped()) {
  4677         copy_to_clone(obj, alloc_obj, obj_size, true, false);
  4679         // Present the results of the copy.
  4680         result_reg->init_req(_array_path, control());
  4681         result_val->init_req(_array_path, alloc_obj);
  4682         result_i_o ->set_req(_array_path, i_o());
  4683         result_mem ->set_req(_array_path, reset_memory());
  4687     // We only go to the instance fast case code if we pass a number of guards.
  4688     // The paths which do not pass are accumulated in the slow_region.
  4689     RegionNode* slow_region = new (C) RegionNode(1);
  4690     record_for_igvn(slow_region);
  4691     if (!stopped()) {
  4692       // It's an instance (we did array above).  Make the slow-path tests.
  4693       // If this is a virtual call, we generate a funny guard.  We grab
  4694       // the vtable entry corresponding to clone() from the target object.
  4695       // If the target method which we are calling happens to be the
  4696       // Object clone() method, we pass the guard.  We do not need this
  4697       // guard for non-virtual calls; the caller is known to be the native
  4698       // Object clone().
  4699       if (is_virtual) {
  4700         generate_virtual_guard(obj_klass, slow_region);
  4703       // The object must be cloneable and must not have a finalizer.
  4704       // Both of these conditions may be checked in a single test.
  4705       // We could optimize the cloneable test further, but we don't care.
  4706       generate_access_flags_guard(obj_klass,
  4707                                   // Test both conditions:
  4708                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
  4709                                   // Must be cloneable but not finalizer:
  4710                                   JVM_ACC_IS_CLONEABLE,
  4711                                   slow_region);
  4714     if (!stopped()) {
  4715       // It's an instance, and it passed the slow-path tests.
  4716       PreserveJVMState pjvms(this);
  4717       Node* obj_size  = NULL;
  4718       // Need to deoptimize on exception from allocation since Object.clone intrinsic
  4719       // is reexecuted if deoptimization occurs and there could be problems when merging
  4720       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
  4721       Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
  4723       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
  4725       // Present the results of the slow call.
  4726       result_reg->init_req(_instance_path, control());
  4727       result_val->init_req(_instance_path, alloc_obj);
  4728       result_i_o ->set_req(_instance_path, i_o());
  4729       result_mem ->set_req(_instance_path, reset_memory());
  4732     // Generate code for the slow case.  We make a call to clone().
  4733     set_control(_gvn.transform(slow_region));
  4734     if (!stopped()) {
  4735       PreserveJVMState pjvms(this);
  4736       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
  4737       Node* slow_result = set_results_for_java_call(slow_call);
  4738       // this->control() comes from set_results_for_java_call
  4739       result_reg->init_req(_slow_path, control());
  4740       result_val->init_req(_slow_path, slow_result);
  4741       result_i_o ->set_req(_slow_path, i_o());
  4742       result_mem ->set_req(_slow_path, reset_memory());
  4745     // Return the combined state.
  4746     set_control(    _gvn.transform(result_reg));
  4747     set_i_o(        _gvn.transform(result_i_o));
  4748     set_all_memory( _gvn.transform(result_mem));
  4749   } // original reexecute is set back here
  4751   set_result(_gvn.transform(result_val));
  4752   return true;
  4755 //------------------------------basictype2arraycopy----------------------------
  4756 address LibraryCallKit::basictype2arraycopy(BasicType t,
  4757                                             Node* src_offset,
  4758                                             Node* dest_offset,
  4759                                             bool disjoint_bases,
  4760                                             const char* &name,
  4761                                             bool dest_uninitialized) {
  4762   const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
  4763   const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
  4765   bool aligned = false;
  4766   bool disjoint = disjoint_bases;
  4768   // if the offsets are the same, we can treat the memory regions as
  4769   // disjoint, because either the memory regions are in different arrays,
  4770   // or they are identical (which we can treat as disjoint.)  We can also
  4771   // treat a copy with a destination index  less that the source index
  4772   // as disjoint since a low->high copy will work correctly in this case.
  4773   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
  4774       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
  4775     // both indices are constants
  4776     int s_offs = src_offset_inttype->get_con();
  4777     int d_offs = dest_offset_inttype->get_con();
  4778     int element_size = type2aelembytes(t);
  4779     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
  4780               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
  4781     if (s_offs >= d_offs)  disjoint = true;
  4782   } else if (src_offset == dest_offset && src_offset != NULL) {
  4783     // This can occur if the offsets are identical non-constants.
  4784     disjoint = true;
  4787   return StubRoutines::select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
  4791 //------------------------------inline_arraycopy-----------------------
  4792 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
  4793 //                                                      Object dest, int destPos,
  4794 //                                                      int length);
  4795 bool LibraryCallKit::inline_arraycopy() {
  4796   // Get the arguments.
  4797   Node* src         = argument(0);  // type: oop
  4798   Node* src_offset  = argument(1);  // type: int
  4799   Node* dest        = argument(2);  // type: oop
  4800   Node* dest_offset = argument(3);  // type: int
  4801   Node* length      = argument(4);  // type: int
  4803   // Compile time checks.  If any of these checks cannot be verified at compile time,
  4804   // we do not make a fast path for this call.  Instead, we let the call remain as it
  4805   // is.  The checks we choose to mandate at compile time are:
  4806   //
  4807   // (1) src and dest are arrays.
  4808   const Type* src_type  = src->Value(&_gvn);
  4809   const Type* dest_type = dest->Value(&_gvn);
  4810   const TypeAryPtr* top_src  = src_type->isa_aryptr();
  4811   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
  4813   // Do we have the type of src?
  4814   bool has_src = (top_src != NULL && top_src->klass() != NULL);
  4815   // Do we have the type of dest?
  4816   bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
  4817   // Is the type for src from speculation?
  4818   bool src_spec = false;
  4819   // Is the type for dest from speculation?
  4820   bool dest_spec = false;
  4822   if (!has_src || !has_dest) {
  4823     // We don't have sufficient type information, let's see if
  4824     // speculative types can help. We need to have types for both src
  4825     // and dest so that it pays off.
  4827     // Do we already have or could we have type information for src
  4828     bool could_have_src = has_src;
  4829     // Do we already have or could we have type information for dest
  4830     bool could_have_dest = has_dest;
  4832     ciKlass* src_k = NULL;
  4833     if (!has_src) {
  4834       src_k = src_type->speculative_type();
  4835       if (src_k != NULL && src_k->is_array_klass()) {
  4836         could_have_src = true;
  4840     ciKlass* dest_k = NULL;
  4841     if (!has_dest) {
  4842       dest_k = dest_type->speculative_type();
  4843       if (dest_k != NULL && dest_k->is_array_klass()) {
  4844         could_have_dest = true;
  4848     if (could_have_src && could_have_dest) {
  4849       // This is going to pay off so emit the required guards
  4850       if (!has_src) {
  4851         src = maybe_cast_profiled_obj(src, src_k);
  4852         src_type  = _gvn.type(src);
  4853         top_src  = src_type->isa_aryptr();
  4854         has_src = (top_src != NULL && top_src->klass() != NULL);
  4855         src_spec = true;
  4857       if (!has_dest) {
  4858         dest = maybe_cast_profiled_obj(dest, dest_k);
  4859         dest_type  = _gvn.type(dest);
  4860         top_dest  = dest_type->isa_aryptr();
  4861         has_dest = (top_dest != NULL && top_dest->klass() != NULL);
  4862         dest_spec = true;
  4867   if (!has_src || !has_dest) {
  4868     // Conservatively insert a memory barrier on all memory slices.
  4869     // Do not let writes into the source float below the arraycopy.
  4870     insert_mem_bar(Op_MemBarCPUOrder);
  4872     // Call StubRoutines::generic_arraycopy stub.
  4873     generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,
  4874                        src, src_offset, dest, dest_offset, length);
  4876     // Do not let reads from the destination float above the arraycopy.
  4877     // Since we cannot type the arrays, we don't know which slices
  4878     // might be affected.  We could restrict this barrier only to those
  4879     // memory slices which pertain to array elements--but don't bother.
  4880     if (!InsertMemBarAfterArraycopy)
  4881       // (If InsertMemBarAfterArraycopy, there is already one in place.)
  4882       insert_mem_bar(Op_MemBarCPUOrder);
  4883     return true;
  4886   // (2) src and dest arrays must have elements of the same BasicType
  4887   // Figure out the size and type of the elements we will be copying.
  4888   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
  4889   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
  4890   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
  4891   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
  4893   if (src_elem != dest_elem || dest_elem == T_VOID) {
  4894     // The component types are not the same or are not recognized.  Punt.
  4895     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
  4896     generate_slow_arraycopy(TypePtr::BOTTOM,
  4897                             src, src_offset, dest, dest_offset, length,
  4898                             /*dest_uninitialized*/false);
  4899     return true;
  4902   if (src_elem == T_OBJECT) {
  4903     // If both arrays are object arrays then having the exact types
  4904     // for both will remove the need for a subtype check at runtime
  4905     // before the call and may make it possible to pick a faster copy
  4906     // routine (without a subtype check on every element)
  4907     // Do we have the exact type of src?
  4908     bool could_have_src = src_spec;
  4909     // Do we have the exact type of dest?
  4910     bool could_have_dest = dest_spec;
  4911     ciKlass* src_k = top_src->klass();
  4912     ciKlass* dest_k = top_dest->klass();
  4913     if (!src_spec) {
  4914       src_k = src_type->speculative_type();
  4915       if (src_k != NULL && src_k->is_array_klass()) {
  4916           could_have_src = true;
  4919     if (!dest_spec) {
  4920       dest_k = dest_type->speculative_type();
  4921       if (dest_k != NULL && dest_k->is_array_klass()) {
  4922         could_have_dest = true;
  4925     if (could_have_src && could_have_dest) {
  4926       // If we can have both exact types, emit the missing guards
  4927       if (could_have_src && !src_spec) {
  4928         src = maybe_cast_profiled_obj(src, src_k);
  4930       if (could_have_dest && !dest_spec) {
  4931         dest = maybe_cast_profiled_obj(dest, dest_k);
  4936   //---------------------------------------------------------------------------
  4937   // We will make a fast path for this call to arraycopy.
  4939   // We have the following tests left to perform:
  4940   //
  4941   // (3) src and dest must not be null.
  4942   // (4) src_offset must not be negative.
  4943   // (5) dest_offset must not be negative.
  4944   // (6) length must not be negative.
  4945   // (7) src_offset + length must not exceed length of src.
  4946   // (8) dest_offset + length must not exceed length of dest.
  4947   // (9) each element of an oop array must be assignable
  4949   RegionNode* slow_region = new (C) RegionNode(1);
  4950   record_for_igvn(slow_region);
  4952   // (3) operands must not be null
  4953   // We currently perform our null checks with the null_check routine.
  4954   // This means that the null exceptions will be reported in the caller
  4955   // rather than (correctly) reported inside of the native arraycopy call.
  4956   // This should be corrected, given time.  We do our null check with the
  4957   // stack pointer restored.
  4958   src  = null_check(src,  T_ARRAY);
  4959   dest = null_check(dest, T_ARRAY);
  4961   // (4) src_offset must not be negative.
  4962   generate_negative_guard(src_offset, slow_region);
  4964   // (5) dest_offset must not be negative.
  4965   generate_negative_guard(dest_offset, slow_region);
  4967   // (6) length must not be negative (moved to generate_arraycopy()).
  4968   // generate_negative_guard(length, slow_region);
  4970   // (7) src_offset + length must not exceed length of src.
  4971   generate_limit_guard(src_offset, length,
  4972                        load_array_length(src),
  4973                        slow_region);
  4975   // (8) dest_offset + length must not exceed length of dest.
  4976   generate_limit_guard(dest_offset, length,
  4977                        load_array_length(dest),
  4978                        slow_region);
  4980   // (9) each element of an oop array must be assignable
  4981   // The generate_arraycopy subroutine checks this.
  4983   // This is where the memory effects are placed:
  4984   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
  4985   generate_arraycopy(adr_type, dest_elem,
  4986                      src, src_offset, dest, dest_offset, length,
  4987                      false, false, slow_region);
  4989   return true;
  4992 //-----------------------------generate_arraycopy----------------------
  4993 // Generate an optimized call to arraycopy.
  4994 // Caller must guard against non-arrays.
  4995 // Caller must determine a common array basic-type for both arrays.
  4996 // Caller must validate offsets against array bounds.
  4997 // The slow_region has already collected guard failure paths
  4998 // (such as out of bounds length or non-conformable array types).
  4999 // The generated code has this shape, in general:
  5000 //
  5001 //     if (length == 0)  return   // via zero_path
  5002 //     slowval = -1
  5003 //     if (types unknown) {
  5004 //       slowval = call generic copy loop
  5005 //       if (slowval == 0)  return  // via checked_path
  5006 //     } else if (indexes in bounds) {
  5007 //       if ((is object array) && !(array type check)) {
  5008 //         slowval = call checked copy loop
  5009 //         if (slowval == 0)  return  // via checked_path
  5010 //       } else {
  5011 //         call bulk copy loop
  5012 //         return  // via fast_path
  5013 //       }
  5014 //     }
  5015 //     // adjust params for remaining work:
  5016 //     if (slowval != -1) {
  5017 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
  5018 //     }
  5019 //   slow_region:
  5020 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
  5021 //     return  // via slow_call_path
  5022 //
  5023 // This routine is used from several intrinsics:  System.arraycopy,
  5024 // Object.clone (the array subcase), and Arrays.copyOf[Range].
  5025 //
  5026 void
  5027 LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,
  5028                                    BasicType basic_elem_type,
  5029                                    Node* src,  Node* src_offset,
  5030                                    Node* dest, Node* dest_offset,
  5031                                    Node* copy_length,
  5032                                    bool disjoint_bases,
  5033                                    bool length_never_negative,
  5034                                    RegionNode* slow_region) {
  5036   if (slow_region == NULL) {
  5037     slow_region = new(C) RegionNode(1);
  5038     record_for_igvn(slow_region);
  5041   Node* original_dest      = dest;
  5042   AllocateArrayNode* alloc = NULL;  // used for zeroing, if needed
  5043   bool  dest_uninitialized = false;
  5045   // See if this is the initialization of a newly-allocated array.
  5046   // If so, we will take responsibility here for initializing it to zero.
  5047   // (Note:  Because tightly_coupled_allocation performs checks on the
  5048   // out-edges of the dest, we need to avoid making derived pointers
  5049   // from it until we have checked its uses.)
  5050   if (ReduceBulkZeroing
  5051       && !ZeroTLAB              // pointless if already zeroed
  5052       && basic_elem_type != T_CONFLICT // avoid corner case
  5053       && !src->eqv_uncast(dest)
  5054       && ((alloc = tightly_coupled_allocation(dest, slow_region))
  5055           != NULL)
  5056       && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
  5057       && alloc->maybe_set_complete(&_gvn)) {
  5058     // "You break it, you buy it."
  5059     InitializeNode* init = alloc->initialization();
  5060     assert(init->is_complete(), "we just did this");
  5061     init->set_complete_with_arraycopy();
  5062     assert(dest->is_CheckCastPP(), "sanity");
  5063     assert(dest->in(0)->in(0) == init, "dest pinned");
  5064     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
  5065     // From this point on, every exit path is responsible for
  5066     // initializing any non-copied parts of the object to zero.
  5067     // Also, if this flag is set we make sure that arraycopy interacts properly
  5068     // with G1, eliding pre-barriers. See CR 6627983.
  5069     dest_uninitialized = true;
  5070   } else {
  5071     // No zeroing elimination here.
  5072     alloc             = NULL;
  5073     //original_dest   = dest;
  5074     //dest_uninitialized = false;
  5077   // Results are placed here:
  5078   enum { fast_path        = 1,  // normal void-returning assembly stub
  5079          checked_path     = 2,  // special assembly stub with cleanup
  5080          slow_call_path   = 3,  // something went wrong; call the VM
  5081          zero_path        = 4,  // bypass when length of copy is zero
  5082          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
  5083          PATH_LIMIT       = 6
  5084   };
  5085   RegionNode* result_region = new(C) RegionNode(PATH_LIMIT);
  5086   PhiNode*    result_i_o    = new(C) PhiNode(result_region, Type::ABIO);
  5087   PhiNode*    result_memory = new(C) PhiNode(result_region, Type::MEMORY, adr_type);
  5088   record_for_igvn(result_region);
  5089   _gvn.set_type_bottom(result_i_o);
  5090   _gvn.set_type_bottom(result_memory);
  5091   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
  5093   // The slow_control path:
  5094   Node* slow_control;
  5095   Node* slow_i_o = i_o();
  5096   Node* slow_mem = memory(adr_type);
  5097   debug_only(slow_control = (Node*) badAddress);
  5099   // Checked control path:
  5100   Node* checked_control = top();
  5101   Node* checked_mem     = NULL;
  5102   Node* checked_i_o     = NULL;
  5103   Node* checked_value   = NULL;
  5105   if (basic_elem_type == T_CONFLICT) {
  5106     assert(!dest_uninitialized, "");
  5107     Node* cv = generate_generic_arraycopy(adr_type,
  5108                                           src, src_offset, dest, dest_offset,
  5109                                           copy_length, dest_uninitialized);
  5110     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  5111     checked_control = control();
  5112     checked_i_o     = i_o();
  5113     checked_mem     = memory(adr_type);
  5114     checked_value   = cv;
  5115     set_control(top());         // no fast path
  5118   Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);
  5119   if (not_pos != NULL) {
  5120     PreserveJVMState pjvms(this);
  5121     set_control(not_pos);
  5123     // (6) length must not be negative.
  5124     if (!length_never_negative) {
  5125       generate_negative_guard(copy_length, slow_region);
  5128     // copy_length is 0.
  5129     if (!stopped() && dest_uninitialized) {
  5130       Node* dest_length = alloc->in(AllocateNode::ALength);
  5131       if (copy_length->eqv_uncast(dest_length)
  5132           || _gvn.find_int_con(dest_length, 1) <= 0) {
  5133         // There is no zeroing to do. No need for a secondary raw memory barrier.
  5134       } else {
  5135         // Clear the whole thing since there are no source elements to copy.
  5136         generate_clear_array(adr_type, dest, basic_elem_type,
  5137                              intcon(0), NULL,
  5138                              alloc->in(AllocateNode::AllocSize));
  5139         // Use a secondary InitializeNode as raw memory barrier.
  5140         // Currently it is needed only on this path since other
  5141         // paths have stub or runtime calls as raw memory barriers.
  5142         InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,
  5143                                                        Compile::AliasIdxRaw,
  5144                                                        top())->as_Initialize();
  5145         init->set_complete(&_gvn);  // (there is no corresponding AllocateNode)
  5149     // Present the results of the fast call.
  5150     result_region->init_req(zero_path, control());
  5151     result_i_o   ->init_req(zero_path, i_o());
  5152     result_memory->init_req(zero_path, memory(adr_type));
  5155   if (!stopped() && dest_uninitialized) {
  5156     // We have to initialize the *uncopied* part of the array to zero.
  5157     // The copy destination is the slice dest[off..off+len].  The other slices
  5158     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
  5159     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
  5160     Node* dest_length = alloc->in(AllocateNode::ALength);
  5161     Node* dest_tail   = _gvn.transform(new(C) AddINode(dest_offset,
  5162                                                           copy_length));
  5164     // If there is a head section that needs zeroing, do it now.
  5165     if (find_int_con(dest_offset, -1) != 0) {
  5166       generate_clear_array(adr_type, dest, basic_elem_type,
  5167                            intcon(0), dest_offset,
  5168                            NULL);
  5171     // Next, perform a dynamic check on the tail length.
  5172     // It is often zero, and we can win big if we prove this.
  5173     // There are two wins:  Avoid generating the ClearArray
  5174     // with its attendant messy index arithmetic, and upgrade
  5175     // the copy to a more hardware-friendly word size of 64 bits.
  5176     Node* tail_ctl = NULL;
  5177     if (!stopped() && !dest_tail->eqv_uncast(dest_length)) {
  5178       Node* cmp_lt   = _gvn.transform(new(C) CmpINode(dest_tail, dest_length));
  5179       Node* bol_lt   = _gvn.transform(new(C) BoolNode(cmp_lt, BoolTest::lt));
  5180       tail_ctl = generate_slow_guard(bol_lt, NULL);
  5181       assert(tail_ctl != NULL || !stopped(), "must be an outcome");
  5184     // At this point, let's assume there is no tail.
  5185     if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {
  5186       // There is no tail.  Try an upgrade to a 64-bit copy.
  5187       bool didit = false;
  5188       { PreserveJVMState pjvms(this);
  5189         didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,
  5190                                          src, src_offset, dest, dest_offset,
  5191                                          dest_size, dest_uninitialized);
  5192         if (didit) {
  5193           // Present the results of the block-copying fast call.
  5194           result_region->init_req(bcopy_path, control());
  5195           result_i_o   ->init_req(bcopy_path, i_o());
  5196           result_memory->init_req(bcopy_path, memory(adr_type));
  5199       if (didit)
  5200         set_control(top());     // no regular fast path
  5203     // Clear the tail, if any.
  5204     if (tail_ctl != NULL) {
  5205       Node* notail_ctl = stopped() ? NULL : control();
  5206       set_control(tail_ctl);
  5207       if (notail_ctl == NULL) {
  5208         generate_clear_array(adr_type, dest, basic_elem_type,
  5209                              dest_tail, NULL,
  5210                              dest_size);
  5211       } else {
  5212         // Make a local merge.
  5213         Node* done_ctl = new(C) RegionNode(3);
  5214         Node* done_mem = new(C) PhiNode(done_ctl, Type::MEMORY, adr_type);
  5215         done_ctl->init_req(1, notail_ctl);
  5216         done_mem->init_req(1, memory(adr_type));
  5217         generate_clear_array(adr_type, dest, basic_elem_type,
  5218                              dest_tail, NULL,
  5219                              dest_size);
  5220         done_ctl->init_req(2, control());
  5221         done_mem->init_req(2, memory(adr_type));
  5222         set_control( _gvn.transform(done_ctl));
  5223         set_memory(  _gvn.transform(done_mem), adr_type );
  5228   BasicType copy_type = basic_elem_type;
  5229   assert(basic_elem_type != T_ARRAY, "caller must fix this");
  5230   if (!stopped() && copy_type == T_OBJECT) {
  5231     // If src and dest have compatible element types, we can copy bits.
  5232     // Types S[] and D[] are compatible if D is a supertype of S.
  5233     //
  5234     // If they are not, we will use checked_oop_disjoint_arraycopy,
  5235     // which performs a fast optimistic per-oop check, and backs off
  5236     // further to JVM_ArrayCopy on the first per-oop check that fails.
  5237     // (Actually, we don't move raw bits only; the GC requires card marks.)
  5239     // Get the Klass* for both src and dest
  5240     Node* src_klass  = load_object_klass(src);
  5241     Node* dest_klass = load_object_klass(dest);
  5243     // Generate the subtype check.
  5244     // This might fold up statically, or then again it might not.
  5245     //
  5246     // Non-static example:  Copying List<String>.elements to a new String[].
  5247     // The backing store for a List<String> is always an Object[],
  5248     // but its elements are always type String, if the generic types
  5249     // are correct at the source level.
  5250     //
  5251     // Test S[] against D[], not S against D, because (probably)
  5252     // the secondary supertype cache is less busy for S[] than S.
  5253     // This usually only matters when D is an interface.
  5254     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
  5255     // Plug failing path into checked_oop_disjoint_arraycopy
  5256     if (not_subtype_ctrl != top()) {
  5257       PreserveJVMState pjvms(this);
  5258       set_control(not_subtype_ctrl);
  5259       // (At this point we can assume disjoint_bases, since types differ.)
  5260       int ek_offset = in_bytes(ObjArrayKlass::element_klass_offset());
  5261       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
  5262       Node* n1 = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p1, TypeRawPtr::BOTTOM);
  5263       Node* dest_elem_klass = _gvn.transform(n1);
  5264       Node* cv = generate_checkcast_arraycopy(adr_type,
  5265                                               dest_elem_klass,
  5266                                               src, src_offset, dest, dest_offset,
  5267                                               ConvI2X(copy_length), dest_uninitialized);
  5268       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  5269       checked_control = control();
  5270       checked_i_o     = i_o();
  5271       checked_mem     = memory(adr_type);
  5272       checked_value   = cv;
  5274     // At this point we know we do not need type checks on oop stores.
  5276     // Let's see if we need card marks:
  5277     if (alloc != NULL && use_ReduceInitialCardMarks()) {
  5278       // If we do not need card marks, copy using the jint or jlong stub.
  5279       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
  5280       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
  5281              "sizes agree");
  5285   if (!stopped()) {
  5286     // Generate the fast path, if possible.
  5287     PreserveJVMState pjvms(this);
  5288     generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,
  5289                                  src, src_offset, dest, dest_offset,
  5290                                  ConvI2X(copy_length), dest_uninitialized);
  5292     // Present the results of the fast call.
  5293     result_region->init_req(fast_path, control());
  5294     result_i_o   ->init_req(fast_path, i_o());
  5295     result_memory->init_req(fast_path, memory(adr_type));
  5298   // Here are all the slow paths up to this point, in one bundle:
  5299   slow_control = top();
  5300   if (slow_region != NULL)
  5301     slow_control = _gvn.transform(slow_region);
  5302   DEBUG_ONLY(slow_region = (RegionNode*)badAddress);
  5304   set_control(checked_control);
  5305   if (!stopped()) {
  5306     // Clean up after the checked call.
  5307     // The returned value is either 0 or -1^K,
  5308     // where K = number of partially transferred array elements.
  5309     Node* cmp = _gvn.transform(new(C) CmpINode(checked_value, intcon(0)));
  5310     Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq));
  5311     IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
  5313     // If it is 0, we are done, so transfer to the end.
  5314     Node* checks_done = _gvn.transform(new(C) IfTrueNode(iff));
  5315     result_region->init_req(checked_path, checks_done);
  5316     result_i_o   ->init_req(checked_path, checked_i_o);
  5317     result_memory->init_req(checked_path, checked_mem);
  5319     // If it is not zero, merge into the slow call.
  5320     set_control( _gvn.transform(new(C) IfFalseNode(iff) ));
  5321     RegionNode* slow_reg2 = new(C) RegionNode(3);
  5322     PhiNode*    slow_i_o2 = new(C) PhiNode(slow_reg2, Type::ABIO);
  5323     PhiNode*    slow_mem2 = new(C) PhiNode(slow_reg2, Type::MEMORY, adr_type);
  5324     record_for_igvn(slow_reg2);
  5325     slow_reg2  ->init_req(1, slow_control);
  5326     slow_i_o2  ->init_req(1, slow_i_o);
  5327     slow_mem2  ->init_req(1, slow_mem);
  5328     slow_reg2  ->init_req(2, control());
  5329     slow_i_o2  ->init_req(2, checked_i_o);
  5330     slow_mem2  ->init_req(2, checked_mem);
  5332     slow_control = _gvn.transform(slow_reg2);
  5333     slow_i_o     = _gvn.transform(slow_i_o2);
  5334     slow_mem     = _gvn.transform(slow_mem2);
  5336     if (alloc != NULL) {
  5337       // We'll restart from the very beginning, after zeroing the whole thing.
  5338       // This can cause double writes, but that's OK since dest is brand new.
  5339       // So we ignore the low 31 bits of the value returned from the stub.
  5340     } else {
  5341       // We must continue the copy exactly where it failed, or else
  5342       // another thread might see the wrong number of writes to dest.
  5343       Node* checked_offset = _gvn.transform(new(C) XorINode(checked_value, intcon(-1)));
  5344       Node* slow_offset    = new(C) PhiNode(slow_reg2, TypeInt::INT);
  5345       slow_offset->init_req(1, intcon(0));
  5346       slow_offset->init_req(2, checked_offset);
  5347       slow_offset  = _gvn.transform(slow_offset);
  5349       // Adjust the arguments by the conditionally incoming offset.
  5350       Node* src_off_plus  = _gvn.transform(new(C) AddINode(src_offset,  slow_offset));
  5351       Node* dest_off_plus = _gvn.transform(new(C) AddINode(dest_offset, slow_offset));
  5352       Node* length_minus  = _gvn.transform(new(C) SubINode(copy_length, slow_offset));
  5354       // Tweak the node variables to adjust the code produced below:
  5355       src_offset  = src_off_plus;
  5356       dest_offset = dest_off_plus;
  5357       copy_length = length_minus;
  5361   set_control(slow_control);
  5362   if (!stopped()) {
  5363     // Generate the slow path, if needed.
  5364     PreserveJVMState pjvms(this);   // replace_in_map may trash the map
  5366     set_memory(slow_mem, adr_type);
  5367     set_i_o(slow_i_o);
  5369     if (dest_uninitialized) {
  5370       generate_clear_array(adr_type, dest, basic_elem_type,
  5371                            intcon(0), NULL,
  5372                            alloc->in(AllocateNode::AllocSize));
  5375     generate_slow_arraycopy(adr_type,
  5376                             src, src_offset, dest, dest_offset,
  5377                             copy_length, /*dest_uninitialized*/false);
  5379     result_region->init_req(slow_call_path, control());
  5380     result_i_o   ->init_req(slow_call_path, i_o());
  5381     result_memory->init_req(slow_call_path, memory(adr_type));
  5384   // Remove unused edges.
  5385   for (uint i = 1; i < result_region->req(); i++) {
  5386     if (result_region->in(i) == NULL)
  5387       result_region->init_req(i, top());
  5390   // Finished; return the combined state.
  5391   set_control( _gvn.transform(result_region));
  5392   set_i_o(     _gvn.transform(result_i_o)    );
  5393   set_memory(  _gvn.transform(result_memory), adr_type );
  5395   // The memory edges above are precise in order to model effects around
  5396   // array copies accurately to allow value numbering of field loads around
  5397   // arraycopy.  Such field loads, both before and after, are common in Java
  5398   // collections and similar classes involving header/array data structures.
  5399   //
  5400   // But with low number of register or when some registers are used or killed
  5401   // by arraycopy calls it causes registers spilling on stack. See 6544710.
  5402   // The next memory barrier is added to avoid it. If the arraycopy can be
  5403   // optimized away (which it can, sometimes) then we can manually remove
  5404   // the membar also.
  5405   //
  5406   // Do not let reads from the cloned object float above the arraycopy.
  5407   if (alloc != NULL) {
  5408     // Do not let stores that initialize this object be reordered with
  5409     // a subsequent store that would make this object accessible by
  5410     // other threads.
  5411     // Record what AllocateNode this StoreStore protects so that
  5412     // escape analysis can go from the MemBarStoreStoreNode to the
  5413     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
  5414     // based on the escape status of the AllocateNode.
  5415     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
  5416   } else if (InsertMemBarAfterArraycopy)
  5417     insert_mem_bar(Op_MemBarCPUOrder);
  5421 // Helper function which determines if an arraycopy immediately follows
  5422 // an allocation, with no intervening tests or other escapes for the object.
  5423 AllocateArrayNode*
  5424 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
  5425                                            RegionNode* slow_region) {
  5426   if (stopped())             return NULL;  // no fast path
  5427   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
  5429   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
  5430   if (alloc == NULL)  return NULL;
  5432   Node* rawmem = memory(Compile::AliasIdxRaw);
  5433   // Is the allocation's memory state untouched?
  5434   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
  5435     // Bail out if there have been raw-memory effects since the allocation.
  5436     // (Example:  There might have been a call or safepoint.)
  5437     return NULL;
  5439   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
  5440   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
  5441     return NULL;
  5444   // There must be no unexpected observers of this allocation.
  5445   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
  5446     Node* obs = ptr->fast_out(i);
  5447     if (obs != this->map()) {
  5448       return NULL;
  5452   // This arraycopy must unconditionally follow the allocation of the ptr.
  5453   Node* alloc_ctl = ptr->in(0);
  5454   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
  5456   Node* ctl = control();
  5457   while (ctl != alloc_ctl) {
  5458     // There may be guards which feed into the slow_region.
  5459     // Any other control flow means that we might not get a chance
  5460     // to finish initializing the allocated object.
  5461     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
  5462       IfNode* iff = ctl->in(0)->as_If();
  5463       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
  5464       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
  5465       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
  5466         ctl = iff->in(0);       // This test feeds the known slow_region.
  5467         continue;
  5469       // One more try:  Various low-level checks bottom out in
  5470       // uncommon traps.  If the debug-info of the trap omits
  5471       // any reference to the allocation, as we've already
  5472       // observed, then there can be no objection to the trap.
  5473       bool found_trap = false;
  5474       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
  5475         Node* obs = not_ctl->fast_out(j);
  5476         if (obs->in(0) == not_ctl && obs->is_Call() &&
  5477             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
  5478           found_trap = true; break;
  5481       if (found_trap) {
  5482         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
  5483         continue;
  5486     return NULL;
  5489   // If we get this far, we have an allocation which immediately
  5490   // precedes the arraycopy, and we can take over zeroing the new object.
  5491   // The arraycopy will finish the initialization, and provide
  5492   // a new control state to which we will anchor the destination pointer.
  5494   return alloc;
  5497 // Helper for initialization of arrays, creating a ClearArray.
  5498 // It writes zero bits in [start..end), within the body of an array object.
  5499 // The memory effects are all chained onto the 'adr_type' alias category.
  5500 //
  5501 // Since the object is otherwise uninitialized, we are free
  5502 // to put a little "slop" around the edges of the cleared area,
  5503 // as long as it does not go back into the array's header,
  5504 // or beyond the array end within the heap.
  5505 //
  5506 // The lower edge can be rounded down to the nearest jint and the
  5507 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
  5508 //
  5509 // Arguments:
  5510 //   adr_type           memory slice where writes are generated
  5511 //   dest               oop of the destination array
  5512 //   basic_elem_type    element type of the destination
  5513 //   slice_idx          array index of first element to store
  5514 //   slice_len          number of elements to store (or NULL)
  5515 //   dest_size          total size in bytes of the array object
  5516 //
  5517 // Exactly one of slice_len or dest_size must be non-NULL.
  5518 // If dest_size is non-NULL, zeroing extends to the end of the object.
  5519 // If slice_len is non-NULL, the slice_idx value must be a constant.
  5520 void
  5521 LibraryCallKit::generate_clear_array(const TypePtr* adr_type,
  5522                                      Node* dest,
  5523                                      BasicType basic_elem_type,
  5524                                      Node* slice_idx,
  5525                                      Node* slice_len,
  5526                                      Node* dest_size) {
  5527   // one or the other but not both of slice_len and dest_size:
  5528   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
  5529   if (slice_len == NULL)  slice_len = top();
  5530   if (dest_size == NULL)  dest_size = top();
  5532   // operate on this memory slice:
  5533   Node* mem = memory(adr_type); // memory slice to operate on
  5535   // scaling and rounding of indexes:
  5536   int scale = exact_log2(type2aelembytes(basic_elem_type));
  5537   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  5538   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
  5539   int bump_bit  = (-1 << scale) & BytesPerInt;
  5541   // determine constant starts and ends
  5542   const intptr_t BIG_NEG = -128;
  5543   assert(BIG_NEG + 2*abase < 0, "neg enough");
  5544   intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);
  5545   intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);
  5546   if (slice_len_con == 0) {
  5547     return;                     // nothing to do here
  5549   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
  5550   intptr_t end_con   = find_intptr_t_con(dest_size, -1);
  5551   if (slice_idx_con >= 0 && slice_len_con >= 0) {
  5552     assert(end_con < 0, "not two cons");
  5553     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
  5554                        BytesPerLong);
  5557   if (start_con >= 0 && end_con >= 0) {
  5558     // Constant start and end.  Simple.
  5559     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5560                                        start_con, end_con, &_gvn);
  5561   } else if (start_con >= 0 && dest_size != top()) {
  5562     // Constant start, pre-rounded end after the tail of the array.
  5563     Node* end = dest_size;
  5564     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5565                                        start_con, end, &_gvn);
  5566   } else if (start_con >= 0 && slice_len != top()) {
  5567     // Constant start, non-constant end.  End needs rounding up.
  5568     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
  5569     intptr_t end_base  = abase + (slice_idx_con << scale);
  5570     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
  5571     Node*    end       = ConvI2X(slice_len);
  5572     if (scale != 0)
  5573       end = _gvn.transform(new(C) LShiftXNode(end, intcon(scale) ));
  5574     end_base += end_round;
  5575     end = _gvn.transform(new(C) AddXNode(end, MakeConX(end_base)));
  5576     end = _gvn.transform(new(C) AndXNode(end, MakeConX(~end_round)));
  5577     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5578                                        start_con, end, &_gvn);
  5579   } else if (start_con < 0 && dest_size != top()) {
  5580     // Non-constant start, pre-rounded end after the tail of the array.
  5581     // This is almost certainly a "round-to-end" operation.
  5582     Node* start = slice_idx;
  5583     start = ConvI2X(start);
  5584     if (scale != 0)
  5585       start = _gvn.transform(new(C) LShiftXNode( start, intcon(scale) ));
  5586     start = _gvn.transform(new(C) AddXNode(start, MakeConX(abase)));
  5587     if ((bump_bit | clear_low) != 0) {
  5588       int to_clear = (bump_bit | clear_low);
  5589       // Align up mod 8, then store a jint zero unconditionally
  5590       // just before the mod-8 boundary.
  5591       if (((abase + bump_bit) & ~to_clear) - bump_bit
  5592           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
  5593         bump_bit = 0;
  5594         assert((abase & to_clear) == 0, "array base must be long-aligned");
  5595       } else {
  5596         // Bump 'start' up to (or past) the next jint boundary:
  5597         start = _gvn.transform(new(C) AddXNode(start, MakeConX(bump_bit)));
  5598         assert((abase & clear_low) == 0, "array base must be int-aligned");
  5600       // Round bumped 'start' down to jlong boundary in body of array.
  5601       start = _gvn.transform(new(C) AndXNode(start, MakeConX(~to_clear)));
  5602       if (bump_bit != 0) {
  5603         // Store a zero to the immediately preceding jint:
  5604         Node* x1 = _gvn.transform(new(C) AddXNode(start, MakeConX(-bump_bit)));
  5605         Node* p1 = basic_plus_adr(dest, x1);
  5606         mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT, MemNode::unordered);
  5607         mem = _gvn.transform(mem);
  5610     Node* end = dest_size; // pre-rounded
  5611     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5612                                        start, end, &_gvn);
  5613   } else {
  5614     // Non-constant start, unrounded non-constant end.
  5615     // (Nobody zeroes a random midsection of an array using this routine.)
  5616     ShouldNotReachHere();       // fix caller
  5619   // Done.
  5620   set_memory(mem, adr_type);
  5624 bool
  5625 LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,
  5626                                          BasicType basic_elem_type,
  5627                                          AllocateNode* alloc,
  5628                                          Node* src,  Node* src_offset,
  5629                                          Node* dest, Node* dest_offset,
  5630                                          Node* dest_size, bool dest_uninitialized) {
  5631   // See if there is an advantage from block transfer.
  5632   int scale = exact_log2(type2aelembytes(basic_elem_type));
  5633   if (scale >= LogBytesPerLong)
  5634     return false;               // it is already a block transfer
  5636   // Look at the alignment of the starting offsets.
  5637   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  5639   intptr_t src_off_con  = (intptr_t) find_int_con(src_offset, -1);
  5640   intptr_t dest_off_con = (intptr_t) find_int_con(dest_offset, -1);
  5641   if (src_off_con < 0 || dest_off_con < 0)
  5642     // At present, we can only understand constants.
  5643     return false;
  5645   intptr_t src_off  = abase + (src_off_con  << scale);
  5646   intptr_t dest_off = abase + (dest_off_con << scale);
  5648   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
  5649     // Non-aligned; too bad.
  5650     // One more chance:  Pick off an initial 32-bit word.
  5651     // This is a common case, since abase can be odd mod 8.
  5652     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
  5653         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
  5654       Node* sptr = basic_plus_adr(src,  src_off);
  5655       Node* dptr = basic_plus_adr(dest, dest_off);
  5656       Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
  5657       store_to_memory(control(), dptr, sval, T_INT, adr_type, MemNode::unordered);
  5658       src_off += BytesPerInt;
  5659       dest_off += BytesPerInt;
  5660     } else {
  5661       return false;
  5664   assert(src_off % BytesPerLong == 0, "");
  5665   assert(dest_off % BytesPerLong == 0, "");
  5667   // Do this copy by giant steps.
  5668   Node* sptr  = basic_plus_adr(src,  src_off);
  5669   Node* dptr  = basic_plus_adr(dest, dest_off);
  5670   Node* countx = dest_size;
  5671   countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(dest_off)));
  5672   countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong)));
  5674   bool disjoint_bases = true;   // since alloc != NULL
  5675   generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,
  5676                                sptr, NULL, dptr, NULL, countx, dest_uninitialized);
  5678   return true;
  5682 // Helper function; generates code for the slow case.
  5683 // We make a call to a runtime method which emulates the native method,
  5684 // but without the native wrapper overhead.
  5685 void
  5686 LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,
  5687                                         Node* src,  Node* src_offset,
  5688                                         Node* dest, Node* dest_offset,
  5689                                         Node* copy_length, bool dest_uninitialized) {
  5690   assert(!dest_uninitialized, "Invariant");
  5691   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,
  5692                                  OptoRuntime::slow_arraycopy_Type(),
  5693                                  OptoRuntime::slow_arraycopy_Java(),
  5694                                  "slow_arraycopy", adr_type,
  5695                                  src, src_offset, dest, dest_offset,
  5696                                  copy_length);
  5698   // Handle exceptions thrown by this fellow:
  5699   make_slow_call_ex(call, env()->Throwable_klass(), false);
  5702 // Helper function; generates code for cases requiring runtime checks.
  5703 Node*
  5704 LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,
  5705                                              Node* dest_elem_klass,
  5706                                              Node* src,  Node* src_offset,
  5707                                              Node* dest, Node* dest_offset,
  5708                                              Node* copy_length, bool dest_uninitialized) {
  5709   if (stopped())  return NULL;
  5711   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
  5712   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5713     return NULL;
  5716   // Pick out the parameters required to perform a store-check
  5717   // for the target array.  This is an optimistic check.  It will
  5718   // look in each non-null element's class, at the desired klass's
  5719   // super_check_offset, for the desired klass.
  5720   int sco_offset = in_bytes(Klass::super_check_offset_offset());
  5721   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
  5722   Node* n3 = new(C) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr(), TypeInt::INT, MemNode::unordered);
  5723   Node* check_offset = ConvI2X(_gvn.transform(n3));
  5724   Node* check_value  = dest_elem_klass;
  5726   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
  5727   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
  5729   // (We know the arrays are never conjoint, because their types differ.)
  5730   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5731                                  OptoRuntime::checkcast_arraycopy_Type(),
  5732                                  copyfunc_addr, "checkcast_arraycopy", adr_type,
  5733                                  // five arguments, of which two are
  5734                                  // intptr_t (jlong in LP64)
  5735                                  src_start, dest_start,
  5736                                  copy_length XTOP,
  5737                                  check_offset XTOP,
  5738                                  check_value);
  5740   return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  5744 // Helper function; generates code for cases requiring runtime checks.
  5745 Node*
  5746 LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,
  5747                                            Node* src,  Node* src_offset,
  5748                                            Node* dest, Node* dest_offset,
  5749                                            Node* copy_length, bool dest_uninitialized) {
  5750   assert(!dest_uninitialized, "Invariant");
  5751   if (stopped())  return NULL;
  5752   address copyfunc_addr = StubRoutines::generic_arraycopy();
  5753   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5754     return NULL;
  5757   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5758                     OptoRuntime::generic_arraycopy_Type(),
  5759                     copyfunc_addr, "generic_arraycopy", adr_type,
  5760                     src, src_offset, dest, dest_offset, copy_length);
  5762   return _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  5765 // Helper function; generates the fast out-of-line call to an arraycopy stub.
  5766 void
  5767 LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,
  5768                                              BasicType basic_elem_type,
  5769                                              bool disjoint_bases,
  5770                                              Node* src,  Node* src_offset,
  5771                                              Node* dest, Node* dest_offset,
  5772                                              Node* copy_length, bool dest_uninitialized) {
  5773   if (stopped())  return;               // nothing to do
  5775   Node* src_start  = src;
  5776   Node* dest_start = dest;
  5777   if (src_offset != NULL || dest_offset != NULL) {
  5778     assert(src_offset != NULL && dest_offset != NULL, "");
  5779     src_start  = array_element_address(src,  src_offset,  basic_elem_type);
  5780     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
  5783   // Figure out which arraycopy runtime method to call.
  5784   const char* copyfunc_name = "arraycopy";
  5785   address     copyfunc_addr =
  5786       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
  5787                           disjoint_bases, copyfunc_name, dest_uninitialized);
  5789   // Call it.  Note that the count_ix value is not scaled to a byte-size.
  5790   make_runtime_call(RC_LEAF|RC_NO_FP,
  5791                     OptoRuntime::fast_arraycopy_Type(),
  5792                     copyfunc_addr, copyfunc_name, adr_type,
  5793                     src_start, dest_start, copy_length XTOP);
  5796 //-------------inline_encodeISOArray-----------------------------------
  5797 // encode char[] to byte[] in ISO_8859_1
  5798 bool LibraryCallKit::inline_encodeISOArray() {
  5799   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
  5800   // no receiver since it is static method
  5801   Node *src         = argument(0);
  5802   Node *src_offset  = argument(1);
  5803   Node *dst         = argument(2);
  5804   Node *dst_offset  = argument(3);
  5805   Node *length      = argument(4);
  5807   const Type* src_type = src->Value(&_gvn);
  5808   const Type* dst_type = dst->Value(&_gvn);
  5809   const TypeAryPtr* top_src = src_type->isa_aryptr();
  5810   const TypeAryPtr* top_dest = dst_type->isa_aryptr();
  5811   if (top_src  == NULL || top_src->klass()  == NULL ||
  5812       top_dest == NULL || top_dest->klass() == NULL) {
  5813     // failed array check
  5814     return false;
  5817   // Figure out the size and type of the elements we will be copying.
  5818   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5819   BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5820   if (src_elem != T_CHAR || dst_elem != T_BYTE) {
  5821     return false;
  5823   Node* src_start = array_element_address(src, src_offset, src_elem);
  5824   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
  5825   // 'src_start' points to src array + scaled offset
  5826   // 'dst_start' points to dst array + scaled offset
  5828   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
  5829   Node* enc = new (C) EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
  5830   enc = _gvn.transform(enc);
  5831   Node* res_mem = _gvn.transform(new (C) SCMemProjNode(enc));
  5832   set_memory(res_mem, mtype);
  5833   set_result(enc);
  5834   return true;
  5837 //-------------inline_multiplyToLen-----------------------------------
  5838 bool LibraryCallKit::inline_multiplyToLen() {
  5839   assert(UseMultiplyToLenIntrinsic, "not implementated on this platform");
  5841   address stubAddr = StubRoutines::multiplyToLen();
  5842   if (stubAddr == NULL) {
  5843     return false; // Intrinsic's stub is not implemented on this platform
  5845   const char* stubName = "multiplyToLen";
  5847   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
  5849   // no receiver because it is a static method
  5850   Node* x    = argument(0);
  5851   Node* xlen = argument(1);
  5852   Node* y    = argument(2);
  5853   Node* ylen = argument(3);
  5854   Node* z    = argument(4);
  5856   const Type* x_type = x->Value(&_gvn);
  5857   const Type* y_type = y->Value(&_gvn);
  5858   const TypeAryPtr* top_x = x_type->isa_aryptr();
  5859   const TypeAryPtr* top_y = y_type->isa_aryptr();
  5860   if (top_x  == NULL || top_x->klass()  == NULL ||
  5861       top_y == NULL || top_y->klass() == NULL) {
  5862     // failed array check
  5863     return false;
  5866   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5867   BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5868   if (x_elem != T_INT || y_elem != T_INT) {
  5869     return false;
  5872   // Set the original stack and the reexecute bit for the interpreter to reexecute
  5873   // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
  5874   // on the return from z array allocation in runtime.
  5875   { PreserveReexecuteState preexecs(this);
  5876     jvms()->set_should_reexecute(true);
  5878     Node* x_start = array_element_address(x, intcon(0), x_elem);
  5879     Node* y_start = array_element_address(y, intcon(0), y_elem);
  5880     // 'x_start' points to x array + scaled xlen
  5881     // 'y_start' points to y array + scaled ylen
  5883     // Allocate the result array
  5884     Node* zlen = _gvn.transform(new(C) AddINode(xlen, ylen));
  5885     ciKlass* klass = ciTypeArrayKlass::make(T_INT);
  5886     Node* klass_node = makecon(TypeKlassPtr::make(klass));
  5888     IdealKit ideal(this);
  5890 #define __ ideal.
  5891      Node* one = __ ConI(1);
  5892      Node* zero = __ ConI(0);
  5893      IdealVariable need_alloc(ideal), z_alloc(ideal);  __ declarations_done();
  5894      __ set(need_alloc, zero);
  5895      __ set(z_alloc, z);
  5896      __ if_then(z, BoolTest::eq, null()); {
  5897        __ increment (need_alloc, one);
  5898      } __ else_(); {
  5899        // Update graphKit memory and control from IdealKit.
  5900        sync_kit(ideal);
  5901        Node* zlen_arg = load_array_length(z);
  5902        // Update IdealKit memory and control from graphKit.
  5903        __ sync_kit(this);
  5904        __ if_then(zlen_arg, BoolTest::lt, zlen); {
  5905          __ increment (need_alloc, one);
  5906        } __ end_if();
  5907      } __ end_if();
  5909      __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
  5910        // Update graphKit memory and control from IdealKit.
  5911        sync_kit(ideal);
  5912        Node * narr = new_array(klass_node, zlen, 1);
  5913        // Update IdealKit memory and control from graphKit.
  5914        __ sync_kit(this);
  5915        __ set(z_alloc, narr);
  5916      } __ end_if();
  5918      sync_kit(ideal);
  5919      z = __ value(z_alloc);
  5920      // Can't use TypeAryPtr::INTS which uses Bottom offset.
  5921      _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
  5922      // Final sync IdealKit and GraphKit.
  5923      final_sync(ideal);
  5924 #undef __
  5926     Node* z_start = array_element_address(z, intcon(0), T_INT);
  5928     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5929                                    OptoRuntime::multiplyToLen_Type(),
  5930                                    stubAddr, stubName, TypePtr::BOTTOM,
  5931                                    x_start, xlen, y_start, ylen, z_start, zlen);
  5932   } // original reexecute is set back here
  5934   C->set_has_split_ifs(true); // Has chance for split-if optimization
  5935   set_result(z);
  5936   return true;
  5939 //-------------inline_squareToLen------------------------------------
  5940 bool LibraryCallKit::inline_squareToLen() {
  5941   assert(UseSquareToLenIntrinsic, "not implementated on this platform");
  5943   address stubAddr = StubRoutines::squareToLen();
  5944   if (stubAddr == NULL) {
  5945     return false; // Intrinsic's stub is not implemented on this platform
  5947   const char* stubName = "squareToLen";
  5949   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
  5951   Node* x    = argument(0);
  5952   Node* len  = argument(1);
  5953   Node* z    = argument(2);
  5954   Node* zlen = argument(3);
  5956   const Type* x_type = x->Value(&_gvn);
  5957   const Type* z_type = z->Value(&_gvn);
  5958   const TypeAryPtr* top_x = x_type->isa_aryptr();
  5959   const TypeAryPtr* top_z = z_type->isa_aryptr();
  5960   if (top_x  == NULL || top_x->klass()  == NULL ||
  5961       top_z  == NULL || top_z->klass()  == NULL) {
  5962     // failed array check
  5963     return false;
  5966   BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5967   BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  5968   if (x_elem != T_INT || z_elem != T_INT) {
  5969     return false;
  5973   Node* x_start = array_element_address(x, intcon(0), x_elem);
  5974   Node* z_start = array_element_address(z, intcon(0), z_elem);
  5976   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5977                                   OptoRuntime::squareToLen_Type(),
  5978                                   stubAddr, stubName, TypePtr::BOTTOM,
  5979                                   x_start, len, z_start, zlen);
  5981   set_result(z);
  5982   return true;
  5985 //-------------inline_mulAdd------------------------------------------
  5986 bool LibraryCallKit::inline_mulAdd() {
  5987   assert(UseMulAddIntrinsic, "not implementated on this platform");
  5989   address stubAddr = StubRoutines::mulAdd();
  5990   if (stubAddr == NULL) {
  5991     return false; // Intrinsic's stub is not implemented on this platform
  5993   const char* stubName = "mulAdd";
  5995   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
  5997   Node* out      = argument(0);
  5998   Node* in       = argument(1);
  5999   Node* offset   = argument(2);
  6000   Node* len      = argument(3);
  6001   Node* k        = argument(4);
  6003   const Type* out_type = out->Value(&_gvn);
  6004   const Type* in_type = in->Value(&_gvn);
  6005   const TypeAryPtr* top_out = out_type->isa_aryptr();
  6006   const TypeAryPtr* top_in = in_type->isa_aryptr();
  6007   if (top_out  == NULL || top_out->klass()  == NULL ||
  6008       top_in == NULL || top_in->klass() == NULL) {
  6009     // failed array check
  6010     return false;
  6013   BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6014   BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6015   if (out_elem != T_INT || in_elem != T_INT) {
  6016     return false;
  6019   Node* outlen = load_array_length(out);
  6020   Node* new_offset = _gvn.transform(new (C) SubINode(outlen, offset));
  6021   Node* out_start = array_element_address(out, intcon(0), out_elem);
  6022   Node* in_start = array_element_address(in, intcon(0), in_elem);
  6024   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
  6025                                   OptoRuntime::mulAdd_Type(),
  6026                                   stubAddr, stubName, TypePtr::BOTTOM,
  6027                                   out_start,in_start, new_offset, len, k);
  6028   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  6029   set_result(result);
  6030   return true;
  6033 //-------------inline_montgomeryMultiply-----------------------------------
  6034 bool LibraryCallKit::inline_montgomeryMultiply() {
  6035   address stubAddr = StubRoutines::montgomeryMultiply();
  6036   if (stubAddr == NULL) {
  6037     return false; // Intrinsic's stub is not implemented on this platform
  6040   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
  6041   const char* stubName = "montgomery_multiply";
  6043   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
  6045   Node* a    = argument(0);
  6046   Node* b    = argument(1);
  6047   Node* n    = argument(2);
  6048   Node* len  = argument(3);
  6049   Node* inv  = argument(4);
  6050   Node* m    = argument(6);
  6052   const Type* a_type = a->Value(&_gvn);
  6053   const TypeAryPtr* top_a = a_type->isa_aryptr();
  6054   const Type* b_type = b->Value(&_gvn);
  6055   const TypeAryPtr* top_b = b_type->isa_aryptr();
  6056   const Type* n_type = a->Value(&_gvn);
  6057   const TypeAryPtr* top_n = n_type->isa_aryptr();
  6058   const Type* m_type = a->Value(&_gvn);
  6059   const TypeAryPtr* top_m = m_type->isa_aryptr();
  6060   if (top_a  == NULL || top_a->klass()  == NULL ||
  6061       top_b == NULL || top_b->klass()  == NULL ||
  6062       top_n == NULL || top_n->klass()  == NULL ||
  6063       top_m == NULL || top_m->klass()  == NULL) {
  6064     // failed array check
  6065     return false;
  6068   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6069   BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6070   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6071   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6072   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
  6073     return false;
  6076   // Make the call
  6078     Node* a_start = array_element_address(a, intcon(0), a_elem);
  6079     Node* b_start = array_element_address(b, intcon(0), b_elem);
  6080     Node* n_start = array_element_address(n, intcon(0), n_elem);
  6081     Node* m_start = array_element_address(m, intcon(0), m_elem);
  6083     Node* call = NULL;
  6084     if (CCallingConventionRequiresIntsAsLongs) {
  6085       Node* len_I2L = ConvI2L(len);
  6086       call = make_runtime_call(RC_LEAF,
  6087                                OptoRuntime::montgomeryMultiply_Type(),
  6088                                stubAddr, stubName, TypePtr::BOTTOM,
  6089                                a_start, b_start, n_start, len_I2L XTOP, inv,
  6090                                top(), m_start);
  6091     } else {
  6092       call = make_runtime_call(RC_LEAF,
  6093                                OptoRuntime::montgomeryMultiply_Type(),
  6094                                stubAddr, stubName, TypePtr::BOTTOM,
  6095                                a_start, b_start, n_start, len, inv, top(),
  6096                                m_start);
  6098     set_result(m);
  6101   return true;
  6104 bool LibraryCallKit::inline_montgomerySquare() {
  6105   address stubAddr = StubRoutines::montgomerySquare();
  6106   if (stubAddr == NULL) {
  6107     return false; // Intrinsic's stub is not implemented on this platform
  6110   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
  6111   const char* stubName = "montgomery_square";
  6113   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
  6115   Node* a    = argument(0);
  6116   Node* n    = argument(1);
  6117   Node* len  = argument(2);
  6118   Node* inv  = argument(3);
  6119   Node* m    = argument(5);
  6121   const Type* a_type = a->Value(&_gvn);
  6122   const TypeAryPtr* top_a = a_type->isa_aryptr();
  6123   const Type* n_type = a->Value(&_gvn);
  6124   const TypeAryPtr* top_n = n_type->isa_aryptr();
  6125   const Type* m_type = a->Value(&_gvn);
  6126   const TypeAryPtr* top_m = m_type->isa_aryptr();
  6127   if (top_a  == NULL || top_a->klass()  == NULL ||
  6128       top_n == NULL || top_n->klass()  == NULL ||
  6129       top_m == NULL || top_m->klass()  == NULL) {
  6130     // failed array check
  6131     return false;
  6134   BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6135   BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6136   BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6137   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
  6138     return false;
  6141   // Make the call
  6143     Node* a_start = array_element_address(a, intcon(0), a_elem);
  6144     Node* n_start = array_element_address(n, intcon(0), n_elem);
  6145     Node* m_start = array_element_address(m, intcon(0), m_elem);
  6147     Node* call = NULL;
  6148     if (CCallingConventionRequiresIntsAsLongs) {
  6149       Node* len_I2L = ConvI2L(len);
  6150       call = make_runtime_call(RC_LEAF,
  6151                                OptoRuntime::montgomerySquare_Type(),
  6152                                stubAddr, stubName, TypePtr::BOTTOM,
  6153                                a_start, n_start, len_I2L XTOP, inv, top(),
  6154                                m_start);
  6155     } else {
  6156       call = make_runtime_call(RC_LEAF,
  6157                                OptoRuntime::montgomerySquare_Type(),
  6158                                stubAddr, stubName, TypePtr::BOTTOM,
  6159                                a_start, n_start, len, inv, top(),
  6160                                m_start);
  6163     set_result(m);
  6166   return true;
  6170 /**
  6171  * Calculate CRC32 for byte.
  6172  * int java.util.zip.CRC32.update(int crc, int b)
  6173  */
  6174 bool LibraryCallKit::inline_updateCRC32() {
  6175   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
  6176   assert(callee()->signature()->size() == 2, "update has 2 parameters");
  6177   // no receiver since it is static method
  6178   Node* crc  = argument(0); // type: int
  6179   Node* b    = argument(1); // type: int
  6181   /*
  6182    *    int c = ~ crc;
  6183    *    b = timesXtoThe32[(b ^ c) & 0xFF];
  6184    *    b = b ^ (c >>> 8);
  6185    *    crc = ~b;
  6186    */
  6188   Node* M1 = intcon(-1);
  6189   crc = _gvn.transform(new (C) XorINode(crc, M1));
  6190   Node* result = _gvn.transform(new (C) XorINode(crc, b));
  6191   result = _gvn.transform(new (C) AndINode(result, intcon(0xFF)));
  6193   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
  6194   Node* offset = _gvn.transform(new (C) LShiftINode(result, intcon(0x2)));
  6195   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
  6196   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
  6198   crc = _gvn.transform(new (C) URShiftINode(crc, intcon(8)));
  6199   result = _gvn.transform(new (C) XorINode(crc, result));
  6200   result = _gvn.transform(new (C) XorINode(result, M1));
  6201   set_result(result);
  6202   return true;
  6205 /**
  6206  * Calculate CRC32 for byte[] array.
  6207  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
  6208  */
  6209 bool LibraryCallKit::inline_updateBytesCRC32() {
  6210   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
  6211   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
  6212   // no receiver since it is static method
  6213   Node* crc     = argument(0); // type: int
  6214   Node* src     = argument(1); // type: oop
  6215   Node* offset  = argument(2); // type: int
  6216   Node* length  = argument(3); // type: int
  6218   const Type* src_type = src->Value(&_gvn);
  6219   const TypeAryPtr* top_src = src_type->isa_aryptr();
  6220   if (top_src  == NULL || top_src->klass()  == NULL) {
  6221     // failed array check
  6222     return false;
  6225   // Figure out the size and type of the elements we will be copying.
  6226   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6227   if (src_elem != T_BYTE) {
  6228     return false;
  6231   // 'src_start' points to src array + scaled offset
  6232   Node* src_start = array_element_address(src, offset, src_elem);
  6234   // We assume that range check is done by caller.
  6235   // TODO: generate range check (offset+length < src.length) in debug VM.
  6237   // Call the stub.
  6238   address stubAddr = StubRoutines::updateBytesCRC32();
  6239   const char *stubName = "updateBytesCRC32";
  6240   Node* call;
  6241   if (CCallingConventionRequiresIntsAsLongs) {
  6242    call =  make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
  6243                              stubAddr, stubName, TypePtr::BOTTOM,
  6244                              crc XTOP, src_start, length XTOP);
  6245   } else {
  6246     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
  6247                              stubAddr, stubName, TypePtr::BOTTOM,
  6248                              crc, src_start, length);
  6250   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  6251   set_result(result);
  6252   return true;
  6255 /**
  6256  * Calculate CRC32 for ByteBuffer.
  6257  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
  6258  */
  6259 bool LibraryCallKit::inline_updateByteBufferCRC32() {
  6260   assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
  6261   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
  6262   // no receiver since it is static method
  6263   Node* crc     = argument(0); // type: int
  6264   Node* src     = argument(1); // type: long
  6265   Node* offset  = argument(3); // type: int
  6266   Node* length  = argument(4); // type: int
  6268   src = ConvL2X(src);  // adjust Java long to machine word
  6269   Node* base = _gvn.transform(new (C) CastX2PNode(src));
  6270   offset = ConvI2X(offset);
  6272   // 'src_start' points to src array + scaled offset
  6273   Node* src_start = basic_plus_adr(top(), base, offset);
  6275   // Call the stub.
  6276   address stubAddr = StubRoutines::updateBytesCRC32();
  6277   const char *stubName = "updateBytesCRC32";
  6278   Node* call;
  6279   if (CCallingConventionRequiresIntsAsLongs) {
  6280     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
  6281                       stubAddr, stubName, TypePtr::BOTTOM,
  6282                       crc XTOP, src_start, length XTOP);
  6283   } else {
  6284     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
  6285                              stubAddr, stubName, TypePtr::BOTTOM,
  6286                              crc, src_start, length);
  6288   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  6289   set_result(result);
  6290   return true;
  6293 //----------------------------inline_reference_get----------------------------
  6294 // public T java.lang.ref.Reference.get();
  6295 bool LibraryCallKit::inline_reference_get() {
  6296   const int referent_offset = java_lang_ref_Reference::referent_offset;
  6297   guarantee(referent_offset > 0, "should have already been set");
  6299   // Get the argument:
  6300   Node* reference_obj = null_check_receiver();
  6301   if (stopped()) return true;
  6303   Node* adr = basic_plus_adr(reference_obj, reference_obj, referent_offset);
  6305   ciInstanceKlass* klass = env()->Object_klass();
  6306   const TypeOopPtr* object_type = TypeOopPtr::make_from_klass(klass);
  6308   Node* no_ctrl = NULL;
  6309   Node* result = make_load(no_ctrl, adr, object_type, T_OBJECT, MemNode::unordered);
  6311   // Use the pre-barrier to record the value in the referent field
  6312   pre_barrier(false /* do_load */,
  6313               control(),
  6314               NULL /* obj */, NULL /* adr */, max_juint /* alias_idx */, NULL /* val */, NULL /* val_type */,
  6315               result /* pre_val */,
  6316               T_OBJECT);
  6318   // Add memory barrier to prevent commoning reads from this field
  6319   // across safepoint since GC can change its value.
  6320   insert_mem_bar(Op_MemBarCPUOrder);
  6322   set_result(result);
  6323   return true;
  6327 Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
  6328                                               bool is_exact=true, bool is_static=false) {
  6330   const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
  6331   assert(tinst != NULL, "obj is null");
  6332   assert(tinst->klass()->is_loaded(), "obj is not loaded");
  6333   assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
  6335   ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName),
  6336                                                                           ciSymbol::make(fieldTypeString),
  6337                                                                           is_static);
  6338   if (field == NULL) return (Node *) NULL;
  6339   assert (field != NULL, "undefined field");
  6341   // Next code  copied from Parse::do_get_xxx():
  6343   // Compute address and memory type.
  6344   int offset  = field->offset_in_bytes();
  6345   bool is_vol = field->is_volatile();
  6346   ciType* field_klass = field->type();
  6347   assert(field_klass->is_loaded(), "should be loaded");
  6348   const TypePtr* adr_type = C->alias_type(field)->adr_type();
  6349   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
  6350   BasicType bt = field->layout_type();
  6352   // Build the resultant type of the load
  6353   const Type *type;
  6354   if (bt == T_OBJECT) {
  6355     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
  6356   } else {
  6357     type = Type::get_const_basic_type(bt);
  6360   if (support_IRIW_for_not_multiple_copy_atomic_cpu && is_vol) {
  6361     insert_mem_bar(Op_MemBarVolatile);   // StoreLoad barrier
  6363   // Build the load.
  6364   MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered;
  6365   Node* loadedField = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, is_vol);
  6366   // If reference is volatile, prevent following memory ops from
  6367   // floating up past the volatile read.  Also prevents commoning
  6368   // another volatile read.
  6369   if (is_vol) {
  6370     // Memory barrier includes bogus read of value to force load BEFORE membar
  6371     insert_mem_bar(Op_MemBarAcquire, loadedField);
  6373   return loadedField;
  6377 //------------------------------inline_aescrypt_Block-----------------------
  6378 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
  6379   address stubAddr = NULL;
  6380   const char *stubName;
  6381   assert(UseAES, "need AES instruction support");
  6383   switch(id) {
  6384   case vmIntrinsics::_aescrypt_encryptBlock:
  6385     stubAddr = StubRoutines::aescrypt_encryptBlock();
  6386     stubName = "aescrypt_encryptBlock";
  6387     break;
  6388   case vmIntrinsics::_aescrypt_decryptBlock:
  6389     stubAddr = StubRoutines::aescrypt_decryptBlock();
  6390     stubName = "aescrypt_decryptBlock";
  6391     break;
  6393   if (stubAddr == NULL) return false;
  6395   Node* aescrypt_object = argument(0);
  6396   Node* src             = argument(1);
  6397   Node* src_offset      = argument(2);
  6398   Node* dest            = argument(3);
  6399   Node* dest_offset     = argument(4);
  6401   // (1) src and dest are arrays.
  6402   const Type* src_type = src->Value(&_gvn);
  6403   const Type* dest_type = dest->Value(&_gvn);
  6404   const TypeAryPtr* top_src = src_type->isa_aryptr();
  6405   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
  6406   assert (top_src  != NULL && top_src->klass()  != NULL &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
  6408   // for the quick and dirty code we will skip all the checks.
  6409   // we are just trying to get the call to be generated.
  6410   Node* src_start  = src;
  6411   Node* dest_start = dest;
  6412   if (src_offset != NULL || dest_offset != NULL) {
  6413     assert(src_offset != NULL && dest_offset != NULL, "");
  6414     src_start  = array_element_address(src,  src_offset,  T_BYTE);
  6415     dest_start = array_element_address(dest, dest_offset, T_BYTE);
  6418   // now need to get the start of its expanded key array
  6419   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
  6420   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
  6421   if (k_start == NULL) return false;
  6423   if (Matcher::pass_original_key_for_aes()) {
  6424     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
  6425     // compatibility issues between Java key expansion and SPARC crypto instructions
  6426     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
  6427     if (original_k_start == NULL) return false;
  6429     // Call the stub.
  6430     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
  6431                       stubAddr, stubName, TypePtr::BOTTOM,
  6432                       src_start, dest_start, k_start, original_k_start);
  6433   } else {
  6434     // Call the stub.
  6435     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
  6436                       stubAddr, stubName, TypePtr::BOTTOM,
  6437                       src_start, dest_start, k_start);
  6440   return true;
  6443 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
  6444 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
  6445   address stubAddr = NULL;
  6446   const char *stubName = NULL;
  6448   assert(UseAES, "need AES instruction support");
  6450   switch(id) {
  6451   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
  6452     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
  6453     stubName = "cipherBlockChaining_encryptAESCrypt";
  6454     break;
  6455   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
  6456     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
  6457     stubName = "cipherBlockChaining_decryptAESCrypt";
  6458     break;
  6460   if (stubAddr == NULL) return false;
  6462   Node* cipherBlockChaining_object = argument(0);
  6463   Node* src                        = argument(1);
  6464   Node* src_offset                 = argument(2);
  6465   Node* len                        = argument(3);
  6466   Node* dest                       = argument(4);
  6467   Node* dest_offset                = argument(5);
  6469   // (1) src and dest are arrays.
  6470   const Type* src_type = src->Value(&_gvn);
  6471   const Type* dest_type = dest->Value(&_gvn);
  6472   const TypeAryPtr* top_src = src_type->isa_aryptr();
  6473   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
  6474   assert (top_src  != NULL && top_src->klass()  != NULL
  6475           &&  top_dest != NULL && top_dest->klass() != NULL, "args are strange");
  6477   // checks are the responsibility of the caller
  6478   Node* src_start  = src;
  6479   Node* dest_start = dest;
  6480   if (src_offset != NULL || dest_offset != NULL) {
  6481     assert(src_offset != NULL && dest_offset != NULL, "");
  6482     src_start  = array_element_address(src,  src_offset,  T_BYTE);
  6483     dest_start = array_element_address(dest, dest_offset, T_BYTE);
  6486   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
  6487   // (because of the predicated logic executed earlier).
  6488   // so we cast it here safely.
  6489   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
  6491   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
  6492   if (embeddedCipherObj == NULL) return false;
  6494   // cast it to what we know it will be at runtime
  6495   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
  6496   assert(tinst != NULL, "CBC obj is null");
  6497   assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
  6498   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
  6499   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
  6501   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
  6502   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
  6503   const TypeOopPtr* xtype = aklass->as_instance_type();
  6504   Node* aescrypt_object = new(C) CheckCastPPNode(control(), embeddedCipherObj, xtype);
  6505   aescrypt_object = _gvn.transform(aescrypt_object);
  6507   // we need to get the start of the aescrypt_object's expanded key array
  6508   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
  6509   if (k_start == NULL) return false;
  6511   // similarly, get the start address of the r vector
  6512   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B", /*is_exact*/ false);
  6513   if (objRvec == NULL) return false;
  6514   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
  6516   Node* cbcCrypt;
  6517   if (Matcher::pass_original_key_for_aes()) {
  6518     // on SPARC we need to pass the original key since key expansion needs to happen in intrinsics due to
  6519     // compatibility issues between Java key expansion and SPARC crypto instructions
  6520     Node* original_k_start = get_original_key_start_from_aescrypt_object(aescrypt_object);
  6521     if (original_k_start == NULL) return false;
  6523     // Call the stub, passing src_start, dest_start, k_start, r_start, src_len and original_k_start
  6524     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
  6525                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
  6526                                  stubAddr, stubName, TypePtr::BOTTOM,
  6527                                  src_start, dest_start, k_start, r_start, len, original_k_start);
  6528   } else {
  6529     // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
  6530     cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
  6531                                  OptoRuntime::cipherBlockChaining_aescrypt_Type(),
  6532                                  stubAddr, stubName, TypePtr::BOTTOM,
  6533                                  src_start, dest_start, k_start, r_start, len);
  6536   // return cipher length (int)
  6537   Node* retvalue = _gvn.transform(new (C) ProjNode(cbcCrypt, TypeFunc::Parms));
  6538   set_result(retvalue);
  6539   return true;
  6542 //------------------------------get_key_start_from_aescrypt_object-----------------------
  6543 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
  6544 #ifdef PPC64
  6545   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
  6546   // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
  6547   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
  6548   // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
  6549   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);
  6550   assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
  6551   if (objSessionK == NULL) {
  6552     return (Node *) NULL;
  6554   Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);
  6555 #else
  6556   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
  6557 #endif // PPC64
  6558   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
  6559   if (objAESCryptKey == NULL) return (Node *) NULL;
  6561   // now have the array, need to get the start address of the K array
  6562   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
  6563   return k_start;
  6566 //------------------------------get_original_key_start_from_aescrypt_object-----------------------
  6567 Node * LibraryCallKit::get_original_key_start_from_aescrypt_object(Node *aescrypt_object) {
  6568   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "lastKey", "[B", /*is_exact*/ false);
  6569   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
  6570   if (objAESCryptKey == NULL) return (Node *) NULL;
  6572   // now have the array, need to get the start address of the lastKey array
  6573   Node* original_k_start = array_element_address(objAESCryptKey, intcon(0), T_BYTE);
  6574   return original_k_start;
  6577 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
  6578 // Return node representing slow path of predicate check.
  6579 // the pseudo code we want to emulate with this predicate is:
  6580 // for encryption:
  6581 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
  6582 // for decryption:
  6583 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
  6584 //    note cipher==plain is more conservative than the original java code but that's OK
  6585 //
  6586 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
  6587   // The receiver was checked for NULL already.
  6588   Node* objCBC = argument(0);
  6590   // Load embeddedCipher field of CipherBlockChaining object.
  6591   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;", /*is_exact*/ false);
  6593   // get AESCrypt klass for instanceOf check
  6594   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
  6595   // will have same classloader as CipherBlockChaining object
  6596   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
  6597   assert(tinst != NULL, "CBCobj is null");
  6598   assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
  6600   // we want to do an instanceof comparison against the AESCrypt class
  6601   ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
  6602   if (!klass_AESCrypt->is_loaded()) {
  6603     // if AESCrypt is not even loaded, we never take the intrinsic fast path
  6604     Node* ctrl = control();
  6605     set_control(top()); // no regular fast path
  6606     return ctrl;
  6608   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
  6610   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
  6611   Node* cmp_instof  = _gvn.transform(new (C) CmpINode(instof, intcon(1)));
  6612   Node* bool_instof  = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));
  6614   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
  6616   // for encryption, we are done
  6617   if (!decrypting)
  6618     return instof_false;  // even if it is NULL
  6620   // for decryption, we need to add a further check to avoid
  6621   // taking the intrinsic path when cipher and plain are the same
  6622   // see the original java code for why.
  6623   RegionNode* region = new(C) RegionNode(3);
  6624   region->init_req(1, instof_false);
  6625   Node* src = argument(1);
  6626   Node* dest = argument(4);
  6627   Node* cmp_src_dest = _gvn.transform(new (C) CmpPNode(src, dest));
  6628   Node* bool_src_dest = _gvn.transform(new (C) BoolNode(cmp_src_dest, BoolTest::eq));
  6629   Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
  6630   region->init_req(2, src_dest_conjoint);
  6632   record_for_igvn(region);
  6633   return _gvn.transform(region);
  6636 //------------------------------inline_ghash_processBlocks
  6637 bool LibraryCallKit::inline_ghash_processBlocks() {
  6638   address stubAddr;
  6639   const char *stubName;
  6640   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
  6642   stubAddr = StubRoutines::ghash_processBlocks();
  6643   stubName = "ghash_processBlocks";
  6645   Node* data           = argument(0);
  6646   Node* offset         = argument(1);
  6647   Node* len            = argument(2);
  6648   Node* state          = argument(3);
  6649   Node* subkeyH        = argument(4);
  6651   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
  6652   assert(state_start, "state is NULL");
  6653   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
  6654   assert(subkeyH_start, "subkeyH is NULL");
  6655   Node* data_start  = array_element_address(data, offset, T_BYTE);
  6656   assert(data_start, "data is NULL");
  6658   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
  6659                                   OptoRuntime::ghash_processBlocks_Type(),
  6660                                   stubAddr, stubName, TypePtr::BOTTOM,
  6661                                   state_start, subkeyH_start, data_start, len);
  6662   return true;
  6665 //------------------------------inline_sha_implCompress-----------------------
  6666 //
  6667 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
  6668 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
  6669 //
  6670 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
  6671 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
  6672 //
  6673 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
  6674 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
  6675 //
  6676 bool LibraryCallKit::inline_sha_implCompress(vmIntrinsics::ID id) {
  6677   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
  6679   Node* sha_obj = argument(0);
  6680   Node* src     = argument(1); // type oop
  6681   Node* ofs     = argument(2); // type int
  6683   const Type* src_type = src->Value(&_gvn);
  6684   const TypeAryPtr* top_src = src_type->isa_aryptr();
  6685   if (top_src  == NULL || top_src->klass()  == NULL) {
  6686     // failed array check
  6687     return false;
  6689   // Figure out the size and type of the elements we will be copying.
  6690   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6691   if (src_elem != T_BYTE) {
  6692     return false;
  6694   // 'src_start' points to src array + offset
  6695   Node* src_start = array_element_address(src, ofs, src_elem);
  6696   Node* state = NULL;
  6697   address stubAddr;
  6698   const char *stubName;
  6700   switch(id) {
  6701   case vmIntrinsics::_sha_implCompress:
  6702     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
  6703     state = get_state_from_sha_object(sha_obj);
  6704     stubAddr = StubRoutines::sha1_implCompress();
  6705     stubName = "sha1_implCompress";
  6706     break;
  6707   case vmIntrinsics::_sha2_implCompress:
  6708     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
  6709     state = get_state_from_sha_object(sha_obj);
  6710     stubAddr = StubRoutines::sha256_implCompress();
  6711     stubName = "sha256_implCompress";
  6712     break;
  6713   case vmIntrinsics::_sha5_implCompress:
  6714     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
  6715     state = get_state_from_sha5_object(sha_obj);
  6716     stubAddr = StubRoutines::sha512_implCompress();
  6717     stubName = "sha512_implCompress";
  6718     break;
  6719   default:
  6720     fatal_unexpected_iid(id);
  6721     return false;
  6723   if (state == NULL) return false;
  6725   // Call the stub.
  6726   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::sha_implCompress_Type(),
  6727                                  stubAddr, stubName, TypePtr::BOTTOM,
  6728                                  src_start, state);
  6730   return true;
  6733 //------------------------------inline_digestBase_implCompressMB-----------------------
  6734 //
  6735 // Calculate SHA/SHA2/SHA5 for multi-block byte[] array.
  6736 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
  6737 //
  6738 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
  6739   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
  6740          "need SHA1/SHA256/SHA512 instruction support");
  6741   assert((uint)predicate < 3, "sanity");
  6742   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
  6744   Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
  6745   Node* src            = argument(1); // byte[] array
  6746   Node* ofs            = argument(2); // type int
  6747   Node* limit          = argument(3); // type int
  6749   const Type* src_type = src->Value(&_gvn);
  6750   const TypeAryPtr* top_src = src_type->isa_aryptr();
  6751   if (top_src  == NULL || top_src->klass()  == NULL) {
  6752     // failed array check
  6753     return false;
  6755   // Figure out the size and type of the elements we will be copying.
  6756   BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
  6757   if (src_elem != T_BYTE) {
  6758     return false;
  6760   // 'src_start' points to src array + offset
  6761   Node* src_start = array_element_address(src, ofs, src_elem);
  6763   const char* klass_SHA_name = NULL;
  6764   const char* stub_name = NULL;
  6765   address     stub_addr = NULL;
  6766   bool        long_state = false;
  6768   switch (predicate) {
  6769   case 0:
  6770     if (UseSHA1Intrinsics) {
  6771       klass_SHA_name = "sun/security/provider/SHA";
  6772       stub_name = "sha1_implCompressMB";
  6773       stub_addr = StubRoutines::sha1_implCompressMB();
  6775     break;
  6776   case 1:
  6777     if (UseSHA256Intrinsics) {
  6778       klass_SHA_name = "sun/security/provider/SHA2";
  6779       stub_name = "sha256_implCompressMB";
  6780       stub_addr = StubRoutines::sha256_implCompressMB();
  6782     break;
  6783   case 2:
  6784     if (UseSHA512Intrinsics) {
  6785       klass_SHA_name = "sun/security/provider/SHA5";
  6786       stub_name = "sha512_implCompressMB";
  6787       stub_addr = StubRoutines::sha512_implCompressMB();
  6788       long_state = true;
  6790     break;
  6791   default:
  6792     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
  6794   if (klass_SHA_name != NULL) {
  6795     // get DigestBase klass to lookup for SHA klass
  6796     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
  6797     assert(tinst != NULL, "digestBase_obj is not instance???");
  6798     assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
  6800     ciKlass* klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
  6801     assert(klass_SHA->is_loaded(), "predicate checks that this class is loaded");
  6802     ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
  6803     return inline_sha_implCompressMB(digestBase_obj, instklass_SHA, long_state, stub_addr, stub_name, src_start, ofs, limit);
  6805   return false;
  6807 //------------------------------inline_sha_implCompressMB-----------------------
  6808 bool LibraryCallKit::inline_sha_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_SHA,
  6809                                                bool long_state, address stubAddr, const char *stubName,
  6810                                                Node* src_start, Node* ofs, Node* limit) {
  6811   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_SHA);
  6812   const TypeOopPtr* xtype = aklass->as_instance_type();
  6813   Node* sha_obj = new (C) CheckCastPPNode(control(), digestBase_obj, xtype);
  6814   sha_obj = _gvn.transform(sha_obj);
  6816   Node* state;
  6817   if (long_state) {
  6818     state = get_state_from_sha5_object(sha_obj);
  6819   } else {
  6820     state = get_state_from_sha_object(sha_obj);
  6822   if (state == NULL) return false;
  6824   // Call the stub.
  6825   Node *call;
  6826   if (CCallingConventionRequiresIntsAsLongs) {
  6827     call = make_runtime_call(RC_LEAF|RC_NO_FP,
  6828                              OptoRuntime::digestBase_implCompressMB_Type(),
  6829                              stubAddr, stubName, TypePtr::BOTTOM,
  6830                              src_start, state, ofs XTOP, limit XTOP);
  6831   } else {
  6832     call = make_runtime_call(RC_LEAF|RC_NO_FP,
  6833                              OptoRuntime::digestBase_implCompressMB_Type(),
  6834                              stubAddr, stubName, TypePtr::BOTTOM,
  6835                              src_start, state, ofs, limit);
  6837   // return ofs (int)
  6838   Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms));
  6839   set_result(result);
  6841   return true;
  6844 //------------------------------get_state_from_sha_object-----------------------
  6845 Node * LibraryCallKit::get_state_from_sha_object(Node *sha_object) {
  6846   Node* sha_state = load_field_from_object(sha_object, "state", "[I", /*is_exact*/ false);
  6847   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA/SHA2");
  6848   if (sha_state == NULL) return (Node *) NULL;
  6850   // now have the array, need to get the start address of the state array
  6851   Node* state = array_element_address(sha_state, intcon(0), T_INT);
  6852   return state;
  6855 //------------------------------get_state_from_sha5_object-----------------------
  6856 Node * LibraryCallKit::get_state_from_sha5_object(Node *sha_object) {
  6857   Node* sha_state = load_field_from_object(sha_object, "state", "[J", /*is_exact*/ false);
  6858   assert (sha_state != NULL, "wrong version of sun.security.provider.SHA5");
  6859   if (sha_state == NULL) return (Node *) NULL;
  6861   // now have the array, need to get the start address of the state array
  6862   Node* state = array_element_address(sha_state, intcon(0), T_LONG);
  6863   return state;
  6866 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
  6867 // Return node representing slow path of predicate check.
  6868 // the pseudo code we want to emulate with this predicate is:
  6869 //    if (digestBaseObj instanceof SHA/SHA2/SHA5) do_intrinsic, else do_javapath
  6870 //
  6871 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
  6872   assert(UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics,
  6873          "need SHA1/SHA256/SHA512 instruction support");
  6874   assert((uint)predicate < 3, "sanity");
  6876   // The receiver was checked for NULL already.
  6877   Node* digestBaseObj = argument(0);
  6879   // get DigestBase klass for instanceOf check
  6880   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
  6881   assert(tinst != NULL, "digestBaseObj is null");
  6882   assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
  6884   const char* klass_SHA_name = NULL;
  6885   switch (predicate) {
  6886   case 0:
  6887     if (UseSHA1Intrinsics) {
  6888       // we want to do an instanceof comparison against the SHA class
  6889       klass_SHA_name = "sun/security/provider/SHA";
  6891     break;
  6892   case 1:
  6893     if (UseSHA256Intrinsics) {
  6894       // we want to do an instanceof comparison against the SHA2 class
  6895       klass_SHA_name = "sun/security/provider/SHA2";
  6897     break;
  6898   case 2:
  6899     if (UseSHA512Intrinsics) {
  6900       // we want to do an instanceof comparison against the SHA5 class
  6901       klass_SHA_name = "sun/security/provider/SHA5";
  6903     break;
  6904   default:
  6905     fatal(err_msg_res("unknown SHA intrinsic predicate: %d", predicate));
  6908   ciKlass* klass_SHA = NULL;
  6909   if (klass_SHA_name != NULL) {
  6910     klass_SHA = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_SHA_name));
  6912   if ((klass_SHA == NULL) || !klass_SHA->is_loaded()) {
  6913     // if none of SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
  6914     Node* ctrl = control();
  6915     set_control(top()); // no intrinsic path
  6916     return ctrl;
  6918   ciInstanceKlass* instklass_SHA = klass_SHA->as_instance_klass();
  6920   Node* instofSHA = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass_SHA)));
  6921   Node* cmp_instof = _gvn.transform(new (C) CmpINode(instofSHA, intcon(1)));
  6922   Node* bool_instof = _gvn.transform(new (C) BoolNode(cmp_instof, BoolTest::ne));
  6923   Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
  6925   return instof_false;  // even if it is NULL
  6928 bool LibraryCallKit::inline_profileBoolean() {
  6929   Node* counts = argument(1);
  6930   const TypeAryPtr* ary = NULL;
  6931   ciArray* aobj = NULL;
  6932   if (counts->is_Con()
  6933       && (ary = counts->bottom_type()->isa_aryptr()) != NULL
  6934       && (aobj = ary->const_oop()->as_array()) != NULL
  6935       && (aobj->length() == 2)) {
  6936     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
  6937     jint false_cnt = aobj->element_value(0).as_int();
  6938     jint  true_cnt = aobj->element_value(1).as_int();
  6940     if (C->log() != NULL) {
  6941       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
  6942                      false_cnt, true_cnt);
  6945     if (false_cnt + true_cnt == 0) {
  6946       // According to profile, never executed.
  6947       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
  6948                           Deoptimization::Action_reinterpret);
  6949       return true;
  6952     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
  6953     // is a number of each value occurrences.
  6954     Node* result = argument(0);
  6955     if (false_cnt == 0 || true_cnt == 0) {
  6956       // According to profile, one value has been never seen.
  6957       int expected_val = (false_cnt == 0) ? 1 : 0;
  6959       Node* cmp  = _gvn.transform(new (C) CmpINode(result, intcon(expected_val)));
  6960       Node* test = _gvn.transform(new (C) BoolNode(cmp, BoolTest::eq));
  6962       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
  6963       Node* fast_path = _gvn.transform(new (C) IfTrueNode(check));
  6964       Node* slow_path = _gvn.transform(new (C) IfFalseNode(check));
  6966       { // Slow path: uncommon trap for never seen value and then reexecute
  6967         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
  6968         // the value has been seen at least once.
  6969         PreserveJVMState pjvms(this);
  6970         PreserveReexecuteState preexecs(this);
  6971         jvms()->set_should_reexecute(true);
  6973         set_control(slow_path);
  6974         set_i_o(i_o());
  6976         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
  6977                             Deoptimization::Action_reinterpret);
  6979       // The guard for never seen value enables sharpening of the result and
  6980       // returning a constant. It allows to eliminate branches on the same value
  6981       // later on.
  6982       set_control(fast_path);
  6983       result = intcon(expected_val);
  6985     // Stop profiling.
  6986     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
  6987     // By replacing method body with profile data (represented as ProfileBooleanNode
  6988     // on IR level) we effectively disable profiling.
  6989     // It enables full speed execution once optimized code is generated.
  6990     Node* profile = _gvn.transform(new (C) ProfileBooleanNode(result, false_cnt, true_cnt));
  6991     C->record_for_igvn(profile);
  6992     set_result(profile);
  6993     return true;
  6994   } else {
  6995     // Continue profiling.
  6996     // Profile data isn't available at the moment. So, execute method's bytecode version.
  6997     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
  6998     // is compiled and counters aren't available since corresponding MethodHandle
  6999     // isn't a compile-time constant.
  7000     return false;

mercurial