src/share/vm/opto/library_call.cpp

Fri, 25 Mar 2011 09:35:39 +0100

author
roland
date
Fri, 25 Mar 2011 09:35:39 +0100
changeset 2683
7e88bdae86ec
parent 2667
0e3ed5a14f73
child 2687
3d58a4983660
child 2781
e1162778c1c8
permissions
-rw-r--r--

7029017: Additional architecture support for c2 compiler
Summary: Enables cross building of a c2 VM. Support masking of shift counts when the processor architecture mandates it.
Reviewed-by: kvn, never

     1 /*
     2  * Copyright (c) 1999, 2011, 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/compileLog.hpp"
    29 #include "oops/objArrayKlass.hpp"
    30 #include "opto/addnode.hpp"
    31 #include "opto/callGenerator.hpp"
    32 #include "opto/cfgnode.hpp"
    33 #include "opto/idealKit.hpp"
    34 #include "opto/mulnode.hpp"
    35 #include "opto/parse.hpp"
    36 #include "opto/runtime.hpp"
    37 #include "opto/subnode.hpp"
    38 #include "prims/nativeLookup.hpp"
    39 #include "runtime/sharedRuntime.hpp"
    41 class LibraryIntrinsic : public InlineCallGenerator {
    42   // Extend the set of intrinsics known to the runtime:
    43  public:
    44  private:
    45   bool             _is_virtual;
    46   vmIntrinsics::ID _intrinsic_id;
    48  public:
    49   LibraryIntrinsic(ciMethod* m, bool is_virtual, vmIntrinsics::ID id)
    50     : InlineCallGenerator(m),
    51       _is_virtual(is_virtual),
    52       _intrinsic_id(id)
    53   {
    54   }
    55   virtual bool is_intrinsic() const { return true; }
    56   virtual bool is_virtual()   const { return _is_virtual; }
    57   virtual JVMState* generate(JVMState* jvms);
    58   vmIntrinsics::ID intrinsic_id() const { return _intrinsic_id; }
    59 };
    62 // Local helper class for LibraryIntrinsic:
    63 class LibraryCallKit : public GraphKit {
    64  private:
    65   LibraryIntrinsic* _intrinsic;   // the library intrinsic being called
    67  public:
    68   LibraryCallKit(JVMState* caller, LibraryIntrinsic* intrinsic)
    69     : GraphKit(caller),
    70       _intrinsic(intrinsic)
    71   {
    72   }
    74   ciMethod*         caller()    const    { return jvms()->method(); }
    75   int               bci()       const    { return jvms()->bci(); }
    76   LibraryIntrinsic* intrinsic() const    { return _intrinsic; }
    77   vmIntrinsics::ID  intrinsic_id() const { return _intrinsic->intrinsic_id(); }
    78   ciMethod*         callee()    const    { return _intrinsic->method(); }
    79   ciSignature*      signature() const    { return callee()->signature(); }
    80   int               arg_size()  const    { return callee()->arg_size(); }
    82   bool try_to_inline();
    84   // Helper functions to inline natives
    85   void push_result(RegionNode* region, PhiNode* value);
    86   Node* generate_guard(Node* test, RegionNode* region, float true_prob);
    87   Node* generate_slow_guard(Node* test, RegionNode* region);
    88   Node* generate_fair_guard(Node* test, RegionNode* region);
    89   Node* generate_negative_guard(Node* index, RegionNode* region,
    90                                 // resulting CastII of index:
    91                                 Node* *pos_index = NULL);
    92   Node* generate_nonpositive_guard(Node* index, bool never_negative,
    93                                    // resulting CastII of index:
    94                                    Node* *pos_index = NULL);
    95   Node* generate_limit_guard(Node* offset, Node* subseq_length,
    96                              Node* array_length,
    97                              RegionNode* region);
    98   Node* generate_current_thread(Node* &tls_output);
    99   address basictype2arraycopy(BasicType t, Node *src_offset, Node *dest_offset,
   100                               bool disjoint_bases, const char* &name, bool dest_uninitialized);
   101   Node* load_mirror_from_klass(Node* klass);
   102   Node* load_klass_from_mirror_common(Node* mirror, bool never_see_null,
   103                                       int nargs,
   104                                       RegionNode* region, int null_path,
   105                                       int offset);
   106   Node* load_klass_from_mirror(Node* mirror, bool never_see_null, int nargs,
   107                                RegionNode* region, int null_path) {
   108     int offset = java_lang_Class::klass_offset_in_bytes();
   109     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
   110                                          region, null_path,
   111                                          offset);
   112   }
   113   Node* load_array_klass_from_mirror(Node* mirror, bool never_see_null,
   114                                      int nargs,
   115                                      RegionNode* region, int null_path) {
   116     int offset = java_lang_Class::array_klass_offset_in_bytes();
   117     return load_klass_from_mirror_common(mirror, never_see_null, nargs,
   118                                          region, null_path,
   119                                          offset);
   120   }
   121   Node* generate_access_flags_guard(Node* kls,
   122                                     int modifier_mask, int modifier_bits,
   123                                     RegionNode* region);
   124   Node* generate_interface_guard(Node* kls, RegionNode* region);
   125   Node* generate_array_guard(Node* kls, RegionNode* region) {
   126     return generate_array_guard_common(kls, region, false, false);
   127   }
   128   Node* generate_non_array_guard(Node* kls, RegionNode* region) {
   129     return generate_array_guard_common(kls, region, false, true);
   130   }
   131   Node* generate_objArray_guard(Node* kls, RegionNode* region) {
   132     return generate_array_guard_common(kls, region, true, false);
   133   }
   134   Node* generate_non_objArray_guard(Node* kls, RegionNode* region) {
   135     return generate_array_guard_common(kls, region, true, true);
   136   }
   137   Node* generate_array_guard_common(Node* kls, RegionNode* region,
   138                                     bool obj_array, bool not_array);
   139   Node* generate_virtual_guard(Node* obj_klass, RegionNode* slow_region);
   140   CallJavaNode* generate_method_call(vmIntrinsics::ID method_id,
   141                                      bool is_virtual = false, bool is_static = false);
   142   CallJavaNode* generate_method_call_static(vmIntrinsics::ID method_id) {
   143     return generate_method_call(method_id, false, true);
   144   }
   145   CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) {
   146     return generate_method_call(method_id, true, false);
   147   }
   149   Node* make_string_method_node(int opcode, Node* str1, Node* cnt1, Node* str2, Node* cnt2);
   150   bool inline_string_compareTo();
   151   bool inline_string_indexOf();
   152   Node* string_indexOf(Node* string_object, ciTypeArray* target_array, jint offset, jint cache_i, jint md2_i);
   153   bool inline_string_equals();
   154   Node* pop_math_arg();
   155   bool runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName);
   156   bool inline_math_native(vmIntrinsics::ID id);
   157   bool inline_trig(vmIntrinsics::ID id);
   158   bool inline_trans(vmIntrinsics::ID id);
   159   bool inline_abs(vmIntrinsics::ID id);
   160   bool inline_sqrt(vmIntrinsics::ID id);
   161   bool inline_pow(vmIntrinsics::ID id);
   162   bool inline_exp(vmIntrinsics::ID id);
   163   bool inline_min_max(vmIntrinsics::ID id);
   164   Node* generate_min_max(vmIntrinsics::ID id, Node* x, Node* y);
   165   // This returns Type::AnyPtr, RawPtr, or OopPtr.
   166   int classify_unsafe_addr(Node* &base, Node* &offset);
   167   Node* make_unsafe_address(Node* base, Node* offset);
   168   bool inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile);
   169   bool inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static);
   170   bool inline_unsafe_allocate();
   171   bool inline_unsafe_copyMemory();
   172   bool inline_native_currentThread();
   173   bool inline_native_time_funcs(bool isNano);
   174   bool inline_native_isInterrupted();
   175   bool inline_native_Class_query(vmIntrinsics::ID id);
   176   bool inline_native_subtype_check();
   178   bool inline_native_newArray();
   179   bool inline_native_getLength();
   180   bool inline_array_copyOf(bool is_copyOfRange);
   181   bool inline_array_equals();
   182   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
   183   bool inline_native_clone(bool is_virtual);
   184   bool inline_native_Reflection_getCallerClass();
   185   bool inline_native_AtomicLong_get();
   186   bool inline_native_AtomicLong_attemptUpdate();
   187   bool is_method_invoke_or_aux_frame(JVMState* jvms);
   188   // Helper function for inlining native object hash method
   189   bool inline_native_hashcode(bool is_virtual, bool is_static);
   190   bool inline_native_getClass();
   192   // Helper functions for inlining arraycopy
   193   bool inline_arraycopy();
   194   void generate_arraycopy(const TypePtr* adr_type,
   195                           BasicType basic_elem_type,
   196                           Node* src,  Node* src_offset,
   197                           Node* dest, Node* dest_offset,
   198                           Node* copy_length,
   199                           bool disjoint_bases = false,
   200                           bool length_never_negative = false,
   201                           RegionNode* slow_region = NULL);
   202   AllocateArrayNode* tightly_coupled_allocation(Node* ptr,
   203                                                 RegionNode* slow_region);
   204   void generate_clear_array(const TypePtr* adr_type,
   205                             Node* dest,
   206                             BasicType basic_elem_type,
   207                             Node* slice_off,
   208                             Node* slice_len,
   209                             Node* slice_end);
   210   bool generate_block_arraycopy(const TypePtr* adr_type,
   211                                 BasicType basic_elem_type,
   212                                 AllocateNode* alloc,
   213                                 Node* src,  Node* src_offset,
   214                                 Node* dest, Node* dest_offset,
   215                                 Node* dest_size, bool dest_uninitialized);
   216   void generate_slow_arraycopy(const TypePtr* adr_type,
   217                                Node* src,  Node* src_offset,
   218                                Node* dest, Node* dest_offset,
   219                                Node* copy_length, bool dest_uninitialized);
   220   Node* generate_checkcast_arraycopy(const TypePtr* adr_type,
   221                                      Node* dest_elem_klass,
   222                                      Node* src,  Node* src_offset,
   223                                      Node* dest, Node* dest_offset,
   224                                      Node* copy_length, bool dest_uninitialized);
   225   Node* generate_generic_arraycopy(const TypePtr* adr_type,
   226                                    Node* src,  Node* src_offset,
   227                                    Node* dest, Node* dest_offset,
   228                                    Node* copy_length, bool dest_uninitialized);
   229   void generate_unchecked_arraycopy(const TypePtr* adr_type,
   230                                     BasicType basic_elem_type,
   231                                     bool disjoint_bases,
   232                                     Node* src,  Node* src_offset,
   233                                     Node* dest, Node* dest_offset,
   234                                     Node* copy_length, bool dest_uninitialized);
   235   bool inline_unsafe_CAS(BasicType type);
   236   bool inline_unsafe_ordered_store(BasicType type);
   237   bool inline_fp_conversions(vmIntrinsics::ID id);
   238   bool inline_numberOfLeadingZeros(vmIntrinsics::ID id);
   239   bool inline_numberOfTrailingZeros(vmIntrinsics::ID id);
   240   bool inline_bitCount(vmIntrinsics::ID id);
   241   bool inline_reverseBytes(vmIntrinsics::ID id);
   242 };
   245 //---------------------------make_vm_intrinsic----------------------------
   246 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
   247   vmIntrinsics::ID id = m->intrinsic_id();
   248   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
   250   if (DisableIntrinsic[0] != '\0'
   251       && strstr(DisableIntrinsic, vmIntrinsics::name_at(id)) != NULL) {
   252     // disabled by a user request on the command line:
   253     // example: -XX:DisableIntrinsic=_hashCode,_getClass
   254     return NULL;
   255   }
   257   if (!m->is_loaded()) {
   258     // do not attempt to inline unloaded methods
   259     return NULL;
   260   }
   262   // Only a few intrinsics implement a virtual dispatch.
   263   // They are expensive calls which are also frequently overridden.
   264   if (is_virtual) {
   265     switch (id) {
   266     case vmIntrinsics::_hashCode:
   267     case vmIntrinsics::_clone:
   268       // OK, Object.hashCode and Object.clone intrinsics come in both flavors
   269       break;
   270     default:
   271       return NULL;
   272     }
   273   }
   275   // -XX:-InlineNatives disables nearly all intrinsics:
   276   if (!InlineNatives) {
   277     switch (id) {
   278     case vmIntrinsics::_indexOf:
   279     case vmIntrinsics::_compareTo:
   280     case vmIntrinsics::_equals:
   281     case vmIntrinsics::_equalsC:
   282       break;  // InlineNatives does not control String.compareTo
   283     default:
   284       return NULL;
   285     }
   286   }
   288   switch (id) {
   289   case vmIntrinsics::_compareTo:
   290     if (!SpecialStringCompareTo)  return NULL;
   291     break;
   292   case vmIntrinsics::_indexOf:
   293     if (!SpecialStringIndexOf)  return NULL;
   294     break;
   295   case vmIntrinsics::_equals:
   296     if (!SpecialStringEquals)  return NULL;
   297     break;
   298   case vmIntrinsics::_equalsC:
   299     if (!SpecialArraysEquals)  return NULL;
   300     break;
   301   case vmIntrinsics::_arraycopy:
   302     if (!InlineArrayCopy)  return NULL;
   303     break;
   304   case vmIntrinsics::_copyMemory:
   305     if (StubRoutines::unsafe_arraycopy() == NULL)  return NULL;
   306     if (!InlineArrayCopy)  return NULL;
   307     break;
   308   case vmIntrinsics::_hashCode:
   309     if (!InlineObjectHash)  return NULL;
   310     break;
   311   case vmIntrinsics::_clone:
   312   case vmIntrinsics::_copyOf:
   313   case vmIntrinsics::_copyOfRange:
   314     if (!InlineObjectCopy)  return NULL;
   315     // These also use the arraycopy intrinsic mechanism:
   316     if (!InlineArrayCopy)  return NULL;
   317     break;
   318   case vmIntrinsics::_checkIndex:
   319     // We do not intrinsify this.  The optimizer does fine with it.
   320     return NULL;
   322   case vmIntrinsics::_get_AtomicLong:
   323   case vmIntrinsics::_attemptUpdate:
   324     if (!InlineAtomicLong)  return NULL;
   325     break;
   327   case vmIntrinsics::_getCallerClass:
   328     if (!UseNewReflection)  return NULL;
   329     if (!InlineReflectionGetCallerClass)  return NULL;
   330     if (!JDK_Version::is_gte_jdk14x_version())  return NULL;
   331     break;
   333   case vmIntrinsics::_bitCount_i:
   334   case vmIntrinsics::_bitCount_l:
   335     if (!UsePopCountInstruction)  return NULL;
   336     break;
   338  default:
   339     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
   340     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
   341     break;
   342   }
   344   // -XX:-InlineClassNatives disables natives from the Class class.
   345   // The flag applies to all reflective calls, notably Array.newArray
   346   // (visible to Java programmers as Array.newInstance).
   347   if (m->holder()->name() == ciSymbol::java_lang_Class() ||
   348       m->holder()->name() == ciSymbol::java_lang_reflect_Array()) {
   349     if (!InlineClassNatives)  return NULL;
   350   }
   352   // -XX:-InlineThreadNatives disables natives from the Thread class.
   353   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
   354     if (!InlineThreadNatives)  return NULL;
   355   }
   357   // -XX:-InlineMathNatives disables natives from the Math,Float and Double classes.
   358   if (m->holder()->name() == ciSymbol::java_lang_Math() ||
   359       m->holder()->name() == ciSymbol::java_lang_Float() ||
   360       m->holder()->name() == ciSymbol::java_lang_Double()) {
   361     if (!InlineMathNatives)  return NULL;
   362   }
   364   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
   365   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
   366     if (!InlineUnsafeOps)  return NULL;
   367   }
   369   return new LibraryIntrinsic(m, is_virtual, (vmIntrinsics::ID) id);
   370 }
   372 //----------------------register_library_intrinsics-----------------------
   373 // Initialize this file's data structures, for each Compile instance.
   374 void Compile::register_library_intrinsics() {
   375   // Nothing to do here.
   376 }
   378 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
   379   LibraryCallKit kit(jvms, this);
   380   Compile* C = kit.C;
   381   int nodes = C->unique();
   382 #ifndef PRODUCT
   383   if ((PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) && Verbose) {
   384     char buf[1000];
   385     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
   386     tty->print_cr("Intrinsic %s", str);
   387   }
   388 #endif
   389   if (kit.try_to_inline()) {
   390     if (PrintIntrinsics || PrintInlining NOT_PRODUCT( || PrintOptoInlining) ) {
   391       tty->print("Inlining intrinsic %s%s at bci:%d in",
   392                  vmIntrinsics::name_at(intrinsic_id()),
   393                  (is_virtual() ? " (virtual)" : ""), kit.bci());
   394       kit.caller()->print_short_name(tty);
   395       tty->print_cr(" (%d bytes)", kit.caller()->code_size());
   396     }
   397     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
   398     if (C->log()) {
   399       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
   400                      vmIntrinsics::name_at(intrinsic_id()),
   401                      (is_virtual() ? " virtual='1'" : ""),
   402                      C->unique() - nodes);
   403     }
   404     return kit.transfer_exceptions_into_jvms();
   405   }
   407   if (PrintIntrinsics) {
   408     tty->print("Did not inline intrinsic %s%s at bci:%d in",
   409                vmIntrinsics::name_at(intrinsic_id()),
   410                (is_virtual() ? " (virtual)" : ""), kit.bci());
   411     kit.caller()->print_short_name(tty);
   412     tty->print_cr(" (%d bytes)", kit.caller()->code_size());
   413   }
   414   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
   415   return NULL;
   416 }
   418 bool LibraryCallKit::try_to_inline() {
   419   // Handle symbolic names for otherwise undistinguished boolean switches:
   420   const bool is_store       = true;
   421   const bool is_native_ptr  = true;
   422   const bool is_static      = true;
   424   switch (intrinsic_id()) {
   425   case vmIntrinsics::_hashCode:
   426     return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
   427   case vmIntrinsics::_identityHashCode:
   428     return inline_native_hashcode(/*!virtual*/ false, is_static);
   429   case vmIntrinsics::_getClass:
   430     return inline_native_getClass();
   432   case vmIntrinsics::_dsin:
   433   case vmIntrinsics::_dcos:
   434   case vmIntrinsics::_dtan:
   435   case vmIntrinsics::_dabs:
   436   case vmIntrinsics::_datan2:
   437   case vmIntrinsics::_dsqrt:
   438   case vmIntrinsics::_dexp:
   439   case vmIntrinsics::_dlog:
   440   case vmIntrinsics::_dlog10:
   441   case vmIntrinsics::_dpow:
   442     return inline_math_native(intrinsic_id());
   444   case vmIntrinsics::_min:
   445   case vmIntrinsics::_max:
   446     return inline_min_max(intrinsic_id());
   448   case vmIntrinsics::_arraycopy:
   449     return inline_arraycopy();
   451   case vmIntrinsics::_compareTo:
   452     return inline_string_compareTo();
   453   case vmIntrinsics::_indexOf:
   454     return inline_string_indexOf();
   455   case vmIntrinsics::_equals:
   456     return inline_string_equals();
   458   case vmIntrinsics::_getObject:
   459     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, false);
   460   case vmIntrinsics::_getBoolean:
   461     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, false);
   462   case vmIntrinsics::_getByte:
   463     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, false);
   464   case vmIntrinsics::_getShort:
   465     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, false);
   466   case vmIntrinsics::_getChar:
   467     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, false);
   468   case vmIntrinsics::_getInt:
   469     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, false);
   470   case vmIntrinsics::_getLong:
   471     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, false);
   472   case vmIntrinsics::_getFloat:
   473     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, false);
   474   case vmIntrinsics::_getDouble:
   475     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, false);
   477   case vmIntrinsics::_putObject:
   478     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, false);
   479   case vmIntrinsics::_putBoolean:
   480     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, false);
   481   case vmIntrinsics::_putByte:
   482     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, false);
   483   case vmIntrinsics::_putShort:
   484     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, false);
   485   case vmIntrinsics::_putChar:
   486     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, false);
   487   case vmIntrinsics::_putInt:
   488     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, false);
   489   case vmIntrinsics::_putLong:
   490     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, false);
   491   case vmIntrinsics::_putFloat:
   492     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, false);
   493   case vmIntrinsics::_putDouble:
   494     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, false);
   496   case vmIntrinsics::_getByte_raw:
   497     return inline_unsafe_access(is_native_ptr, !is_store, T_BYTE, false);
   498   case vmIntrinsics::_getShort_raw:
   499     return inline_unsafe_access(is_native_ptr, !is_store, T_SHORT, false);
   500   case vmIntrinsics::_getChar_raw:
   501     return inline_unsafe_access(is_native_ptr, !is_store, T_CHAR, false);
   502   case vmIntrinsics::_getInt_raw:
   503     return inline_unsafe_access(is_native_ptr, !is_store, T_INT, false);
   504   case vmIntrinsics::_getLong_raw:
   505     return inline_unsafe_access(is_native_ptr, !is_store, T_LONG, false);
   506   case vmIntrinsics::_getFloat_raw:
   507     return inline_unsafe_access(is_native_ptr, !is_store, T_FLOAT, false);
   508   case vmIntrinsics::_getDouble_raw:
   509     return inline_unsafe_access(is_native_ptr, !is_store, T_DOUBLE, false);
   510   case vmIntrinsics::_getAddress_raw:
   511     return inline_unsafe_access(is_native_ptr, !is_store, T_ADDRESS, false);
   513   case vmIntrinsics::_putByte_raw:
   514     return inline_unsafe_access(is_native_ptr, is_store, T_BYTE, false);
   515   case vmIntrinsics::_putShort_raw:
   516     return inline_unsafe_access(is_native_ptr, is_store, T_SHORT, false);
   517   case vmIntrinsics::_putChar_raw:
   518     return inline_unsafe_access(is_native_ptr, is_store, T_CHAR, false);
   519   case vmIntrinsics::_putInt_raw:
   520     return inline_unsafe_access(is_native_ptr, is_store, T_INT, false);
   521   case vmIntrinsics::_putLong_raw:
   522     return inline_unsafe_access(is_native_ptr, is_store, T_LONG, false);
   523   case vmIntrinsics::_putFloat_raw:
   524     return inline_unsafe_access(is_native_ptr, is_store, T_FLOAT, false);
   525   case vmIntrinsics::_putDouble_raw:
   526     return inline_unsafe_access(is_native_ptr, is_store, T_DOUBLE, false);
   527   case vmIntrinsics::_putAddress_raw:
   528     return inline_unsafe_access(is_native_ptr, is_store, T_ADDRESS, false);
   530   case vmIntrinsics::_getObjectVolatile:
   531     return inline_unsafe_access(!is_native_ptr, !is_store, T_OBJECT, true);
   532   case vmIntrinsics::_getBooleanVolatile:
   533     return inline_unsafe_access(!is_native_ptr, !is_store, T_BOOLEAN, true);
   534   case vmIntrinsics::_getByteVolatile:
   535     return inline_unsafe_access(!is_native_ptr, !is_store, T_BYTE, true);
   536   case vmIntrinsics::_getShortVolatile:
   537     return inline_unsafe_access(!is_native_ptr, !is_store, T_SHORT, true);
   538   case vmIntrinsics::_getCharVolatile:
   539     return inline_unsafe_access(!is_native_ptr, !is_store, T_CHAR, true);
   540   case vmIntrinsics::_getIntVolatile:
   541     return inline_unsafe_access(!is_native_ptr, !is_store, T_INT, true);
   542   case vmIntrinsics::_getLongVolatile:
   543     return inline_unsafe_access(!is_native_ptr, !is_store, T_LONG, true);
   544   case vmIntrinsics::_getFloatVolatile:
   545     return inline_unsafe_access(!is_native_ptr, !is_store, T_FLOAT, true);
   546   case vmIntrinsics::_getDoubleVolatile:
   547     return inline_unsafe_access(!is_native_ptr, !is_store, T_DOUBLE, true);
   549   case vmIntrinsics::_putObjectVolatile:
   550     return inline_unsafe_access(!is_native_ptr, is_store, T_OBJECT, true);
   551   case vmIntrinsics::_putBooleanVolatile:
   552     return inline_unsafe_access(!is_native_ptr, is_store, T_BOOLEAN, true);
   553   case vmIntrinsics::_putByteVolatile:
   554     return inline_unsafe_access(!is_native_ptr, is_store, T_BYTE, true);
   555   case vmIntrinsics::_putShortVolatile:
   556     return inline_unsafe_access(!is_native_ptr, is_store, T_SHORT, true);
   557   case vmIntrinsics::_putCharVolatile:
   558     return inline_unsafe_access(!is_native_ptr, is_store, T_CHAR, true);
   559   case vmIntrinsics::_putIntVolatile:
   560     return inline_unsafe_access(!is_native_ptr, is_store, T_INT, true);
   561   case vmIntrinsics::_putLongVolatile:
   562     return inline_unsafe_access(!is_native_ptr, is_store, T_LONG, true);
   563   case vmIntrinsics::_putFloatVolatile:
   564     return inline_unsafe_access(!is_native_ptr, is_store, T_FLOAT, true);
   565   case vmIntrinsics::_putDoubleVolatile:
   566     return inline_unsafe_access(!is_native_ptr, is_store, T_DOUBLE, true);
   568   case vmIntrinsics::_prefetchRead:
   569     return inline_unsafe_prefetch(!is_native_ptr, !is_store, !is_static);
   570   case vmIntrinsics::_prefetchWrite:
   571     return inline_unsafe_prefetch(!is_native_ptr, is_store, !is_static);
   572   case vmIntrinsics::_prefetchReadStatic:
   573     return inline_unsafe_prefetch(!is_native_ptr, !is_store, is_static);
   574   case vmIntrinsics::_prefetchWriteStatic:
   575     return inline_unsafe_prefetch(!is_native_ptr, is_store, is_static);
   577   case vmIntrinsics::_compareAndSwapObject:
   578     return inline_unsafe_CAS(T_OBJECT);
   579   case vmIntrinsics::_compareAndSwapInt:
   580     return inline_unsafe_CAS(T_INT);
   581   case vmIntrinsics::_compareAndSwapLong:
   582     return inline_unsafe_CAS(T_LONG);
   584   case vmIntrinsics::_putOrderedObject:
   585     return inline_unsafe_ordered_store(T_OBJECT);
   586   case vmIntrinsics::_putOrderedInt:
   587     return inline_unsafe_ordered_store(T_INT);
   588   case vmIntrinsics::_putOrderedLong:
   589     return inline_unsafe_ordered_store(T_LONG);
   591   case vmIntrinsics::_currentThread:
   592     return inline_native_currentThread();
   593   case vmIntrinsics::_isInterrupted:
   594     return inline_native_isInterrupted();
   596   case vmIntrinsics::_currentTimeMillis:
   597     return inline_native_time_funcs(false);
   598   case vmIntrinsics::_nanoTime:
   599     return inline_native_time_funcs(true);
   600   case vmIntrinsics::_allocateInstance:
   601     return inline_unsafe_allocate();
   602   case vmIntrinsics::_copyMemory:
   603     return inline_unsafe_copyMemory();
   604   case vmIntrinsics::_newArray:
   605     return inline_native_newArray();
   606   case vmIntrinsics::_getLength:
   607     return inline_native_getLength();
   608   case vmIntrinsics::_copyOf:
   609     return inline_array_copyOf(false);
   610   case vmIntrinsics::_copyOfRange:
   611     return inline_array_copyOf(true);
   612   case vmIntrinsics::_equalsC:
   613     return inline_array_equals();
   614   case vmIntrinsics::_clone:
   615     return inline_native_clone(intrinsic()->is_virtual());
   617   case vmIntrinsics::_isAssignableFrom:
   618     return inline_native_subtype_check();
   620   case vmIntrinsics::_isInstance:
   621   case vmIntrinsics::_getModifiers:
   622   case vmIntrinsics::_isInterface:
   623   case vmIntrinsics::_isArray:
   624   case vmIntrinsics::_isPrimitive:
   625   case vmIntrinsics::_getSuperclass:
   626   case vmIntrinsics::_getComponentType:
   627   case vmIntrinsics::_getClassAccessFlags:
   628     return inline_native_Class_query(intrinsic_id());
   630   case vmIntrinsics::_floatToRawIntBits:
   631   case vmIntrinsics::_floatToIntBits:
   632   case vmIntrinsics::_intBitsToFloat:
   633   case vmIntrinsics::_doubleToRawLongBits:
   634   case vmIntrinsics::_doubleToLongBits:
   635   case vmIntrinsics::_longBitsToDouble:
   636     return inline_fp_conversions(intrinsic_id());
   638   case vmIntrinsics::_numberOfLeadingZeros_i:
   639   case vmIntrinsics::_numberOfLeadingZeros_l:
   640     return inline_numberOfLeadingZeros(intrinsic_id());
   642   case vmIntrinsics::_numberOfTrailingZeros_i:
   643   case vmIntrinsics::_numberOfTrailingZeros_l:
   644     return inline_numberOfTrailingZeros(intrinsic_id());
   646   case vmIntrinsics::_bitCount_i:
   647   case vmIntrinsics::_bitCount_l:
   648     return inline_bitCount(intrinsic_id());
   650   case vmIntrinsics::_reverseBytes_i:
   651   case vmIntrinsics::_reverseBytes_l:
   652   case vmIntrinsics::_reverseBytes_s:
   653   case vmIntrinsics::_reverseBytes_c:
   654     return inline_reverseBytes((vmIntrinsics::ID) intrinsic_id());
   656   case vmIntrinsics::_get_AtomicLong:
   657     return inline_native_AtomicLong_get();
   658   case vmIntrinsics::_attemptUpdate:
   659     return inline_native_AtomicLong_attemptUpdate();
   661   case vmIntrinsics::_getCallerClass:
   662     return inline_native_Reflection_getCallerClass();
   664   default:
   665     // If you get here, it may be that someone has added a new intrinsic
   666     // to the list in vmSymbols.hpp without implementing it here.
   667 #ifndef PRODUCT
   668     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
   669       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
   670                     vmIntrinsics::name_at(intrinsic_id()), intrinsic_id());
   671     }
   672 #endif
   673     return false;
   674   }
   675 }
   677 //------------------------------push_result------------------------------
   678 // Helper function for finishing intrinsics.
   679 void LibraryCallKit::push_result(RegionNode* region, PhiNode* value) {
   680   record_for_igvn(region);
   681   set_control(_gvn.transform(region));
   682   BasicType value_type = value->type()->basic_type();
   683   push_node(value_type, _gvn.transform(value));
   684 }
   686 //------------------------------generate_guard---------------------------
   687 // Helper function for generating guarded fast-slow graph structures.
   688 // The given 'test', if true, guards a slow path.  If the test fails
   689 // then a fast path can be taken.  (We generally hope it fails.)
   690 // In all cases, GraphKit::control() is updated to the fast path.
   691 // The returned value represents the control for the slow path.
   692 // The return value is never 'top'; it is either a valid control
   693 // or NULL if it is obvious that the slow path can never be taken.
   694 // Also, if region and the slow control are not NULL, the slow edge
   695 // is appended to the region.
   696 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
   697   if (stopped()) {
   698     // Already short circuited.
   699     return NULL;
   700   }
   702   // Build an if node and its projections.
   703   // If test is true we take the slow path, which we assume is uncommon.
   704   if (_gvn.type(test) == TypeInt::ZERO) {
   705     // The slow branch is never taken.  No need to build this guard.
   706     return NULL;
   707   }
   709   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
   711   Node* if_slow = _gvn.transform( new (C, 1) IfTrueNode(iff) );
   712   if (if_slow == top()) {
   713     // The slow branch is never taken.  No need to build this guard.
   714     return NULL;
   715   }
   717   if (region != NULL)
   718     region->add_req(if_slow);
   720   Node* if_fast = _gvn.transform( new (C, 1) IfFalseNode(iff) );
   721   set_control(if_fast);
   723   return if_slow;
   724 }
   726 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
   727   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
   728 }
   729 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
   730   return generate_guard(test, region, PROB_FAIR);
   731 }
   733 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
   734                                                      Node* *pos_index) {
   735   if (stopped())
   736     return NULL;                // already stopped
   737   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
   738     return NULL;                // index is already adequately typed
   739   Node* cmp_lt = _gvn.transform( new (C, 3) CmpINode(index, intcon(0)) );
   740   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
   741   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
   742   if (is_neg != NULL && pos_index != NULL) {
   743     // Emulate effect of Parse::adjust_map_after_if.
   744     Node* ccast = new (C, 2) CastIINode(index, TypeInt::POS);
   745     ccast->set_req(0, control());
   746     (*pos_index) = _gvn.transform(ccast);
   747   }
   748   return is_neg;
   749 }
   751 inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_negative,
   752                                                         Node* *pos_index) {
   753   if (stopped())
   754     return NULL;                // already stopped
   755   if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint]
   756     return NULL;                // index is already adequately typed
   757   Node* cmp_le = _gvn.transform( new (C, 3) CmpINode(index, intcon(0)) );
   758   BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le);
   759   Node* bol_le = _gvn.transform( new (C, 2) BoolNode(cmp_le, le_or_eq) );
   760   Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN);
   761   if (is_notp != NULL && pos_index != NULL) {
   762     // Emulate effect of Parse::adjust_map_after_if.
   763     Node* ccast = new (C, 2) CastIINode(index, TypeInt::POS1);
   764     ccast->set_req(0, control());
   765     (*pos_index) = _gvn.transform(ccast);
   766   }
   767   return is_notp;
   768 }
   770 // Make sure that 'position' is a valid limit index, in [0..length].
   771 // There are two equivalent plans for checking this:
   772 //   A. (offset + copyLength)  unsigned<=  arrayLength
   773 //   B. offset  <=  (arrayLength - copyLength)
   774 // We require that all of the values above, except for the sum and
   775 // difference, are already known to be non-negative.
   776 // Plan A is robust in the face of overflow, if offset and copyLength
   777 // are both hugely positive.
   778 //
   779 // Plan B is less direct and intuitive, but it does not overflow at
   780 // all, since the difference of two non-negatives is always
   781 // representable.  Whenever Java methods must perform the equivalent
   782 // check they generally use Plan B instead of Plan A.
   783 // For the moment we use Plan A.
   784 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
   785                                                   Node* subseq_length,
   786                                                   Node* array_length,
   787                                                   RegionNode* region) {
   788   if (stopped())
   789     return NULL;                // already stopped
   790   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
   791   if (zero_offset && _gvn.eqv_uncast(subseq_length, array_length))
   792     return NULL;                // common case of whole-array copy
   793   Node* last = subseq_length;
   794   if (!zero_offset)             // last += offset
   795     last = _gvn.transform( new (C, 3) AddINode(last, offset));
   796   Node* cmp_lt = _gvn.transform( new (C, 3) CmpUNode(array_length, last) );
   797   Node* bol_lt = _gvn.transform( new (C, 2) BoolNode(cmp_lt, BoolTest::lt) );
   798   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
   799   return is_over;
   800 }
   803 //--------------------------generate_current_thread--------------------
   804 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
   805   ciKlass*    thread_klass = env()->Thread_klass();
   806   const Type* thread_type  = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
   807   Node* thread = _gvn.transform(new (C, 1) ThreadLocalNode());
   808   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
   809   Node* threadObj = make_load(NULL, p, thread_type, T_OBJECT);
   810   tls_output = thread;
   811   return threadObj;
   812 }
   815 //------------------------------make_string_method_node------------------------
   816 // Helper method for String intrinsic finctions.
   817 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1, Node* cnt1, Node* str2, Node* cnt2) {
   818   const int value_offset  = java_lang_String::value_offset_in_bytes();
   819   const int count_offset  = java_lang_String::count_offset_in_bytes();
   820   const int offset_offset = java_lang_String::offset_offset_in_bytes();
   822   Node* no_ctrl = NULL;
   824   ciInstanceKlass* klass = env()->String_klass();
   825   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
   827   const TypeAryPtr* value_type =
   828         TypeAryPtr::make(TypePtr::NotNull,
   829                          TypeAry::make(TypeInt::CHAR,TypeInt::POS),
   830                          ciTypeArrayKlass::make(T_CHAR), true, 0);
   832   // Get start addr of string and substring
   833   Node* str1_valuea  = basic_plus_adr(str1, str1, value_offset);
   834   Node* str1_value   = make_load(no_ctrl, str1_valuea, value_type, T_OBJECT, string_type->add_offset(value_offset));
   835   Node* str1_offseta = basic_plus_adr(str1, str1, offset_offset);
   836   Node* str1_offset  = make_load(no_ctrl, str1_offseta, TypeInt::INT, T_INT, string_type->add_offset(offset_offset));
   837   Node* str1_start   = array_element_address(str1_value, str1_offset, T_CHAR);
   839   // Pin loads from String::equals() argument since it could be NULL.
   840   Node* str2_ctrl = (opcode == Op_StrEquals) ? control() : no_ctrl;
   841   Node* str2_valuea  = basic_plus_adr(str2, str2, value_offset);
   842   Node* str2_value   = make_load(str2_ctrl, str2_valuea, value_type, T_OBJECT, string_type->add_offset(value_offset));
   843   Node* str2_offseta = basic_plus_adr(str2, str2, offset_offset);
   844   Node* str2_offset  = make_load(str2_ctrl, str2_offseta, TypeInt::INT, T_INT, string_type->add_offset(offset_offset));
   845   Node* str2_start   = array_element_address(str2_value, str2_offset, T_CHAR);
   847   Node* result = NULL;
   848   switch (opcode) {
   849   case Op_StrIndexOf:
   850     result = new (C, 6) StrIndexOfNode(control(), memory(TypeAryPtr::CHARS),
   851                                        str1_start, cnt1, str2_start, cnt2);
   852     break;
   853   case Op_StrComp:
   854     result = new (C, 6) StrCompNode(control(), memory(TypeAryPtr::CHARS),
   855                                     str1_start, cnt1, str2_start, cnt2);
   856     break;
   857   case Op_StrEquals:
   858     result = new (C, 5) StrEqualsNode(control(), memory(TypeAryPtr::CHARS),
   859                                       str1_start, str2_start, cnt1);
   860     break;
   861   default:
   862     ShouldNotReachHere();
   863     return NULL;
   864   }
   866   // All these intrinsics have checks.
   867   C->set_has_split_ifs(true); // Has chance for split-if optimization
   869   return _gvn.transform(result);
   870 }
   872 //------------------------------inline_string_compareTo------------------------
   873 bool LibraryCallKit::inline_string_compareTo() {
   875   if (!Matcher::has_match_rule(Op_StrComp)) return false;
   877   const int value_offset = java_lang_String::value_offset_in_bytes();
   878   const int count_offset = java_lang_String::count_offset_in_bytes();
   879   const int offset_offset = java_lang_String::offset_offset_in_bytes();
   881   _sp += 2;
   882   Node *argument = pop();  // pop non-receiver first:  it was pushed second
   883   Node *receiver = pop();
   885   // Null check on self without removing any arguments.  The argument
   886   // null check technically happens in the wrong place, which can lead to
   887   // invalid stack traces when string compare is inlined into a method
   888   // which handles NullPointerExceptions.
   889   _sp += 2;
   890   receiver = do_null_check(receiver, T_OBJECT);
   891   argument = do_null_check(argument, T_OBJECT);
   892   _sp -= 2;
   893   if (stopped()) {
   894     return true;
   895   }
   897   ciInstanceKlass* klass = env()->String_klass();
   898   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
   899   Node* no_ctrl = NULL;
   901   // Get counts for string and argument
   902   Node* receiver_cnta = basic_plus_adr(receiver, receiver, count_offset);
   903   Node* receiver_cnt  = make_load(no_ctrl, receiver_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
   905   Node* argument_cnta = basic_plus_adr(argument, argument, count_offset);
   906   Node* argument_cnt  = make_load(no_ctrl, argument_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
   908   Node* compare = make_string_method_node(Op_StrComp, receiver, receiver_cnt, argument, argument_cnt);
   909   push(compare);
   910   return true;
   911 }
   913 //------------------------------inline_string_equals------------------------
   914 bool LibraryCallKit::inline_string_equals() {
   916   if (!Matcher::has_match_rule(Op_StrEquals)) return false;
   918   const int value_offset = java_lang_String::value_offset_in_bytes();
   919   const int count_offset = java_lang_String::count_offset_in_bytes();
   920   const int offset_offset = java_lang_String::offset_offset_in_bytes();
   922   int nargs = 2;
   923   _sp += nargs;
   924   Node* argument = pop();  // pop non-receiver first:  it was pushed second
   925   Node* receiver = pop();
   927   // Null check on self without removing any arguments.  The argument
   928   // null check technically happens in the wrong place, which can lead to
   929   // invalid stack traces when string compare is inlined into a method
   930   // which handles NullPointerExceptions.
   931   _sp += nargs;
   932   receiver = do_null_check(receiver, T_OBJECT);
   933   //should not do null check for argument for String.equals(), because spec
   934   //allows to specify NULL as argument.
   935   _sp -= nargs;
   937   if (stopped()) {
   938     return true;
   939   }
   941   // paths (plus control) merge
   942   RegionNode* region = new (C, 5) RegionNode(5);
   943   Node* phi = new (C, 5) PhiNode(region, TypeInt::BOOL);
   945   // does source == target string?
   946   Node* cmp = _gvn.transform(new (C, 3) CmpPNode(receiver, argument));
   947   Node* bol = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::eq));
   949   Node* if_eq = generate_slow_guard(bol, NULL);
   950   if (if_eq != NULL) {
   951     // receiver == argument
   952     phi->init_req(2, intcon(1));
   953     region->init_req(2, if_eq);
   954   }
   956   // get String klass for instanceOf
   957   ciInstanceKlass* klass = env()->String_klass();
   959   if (!stopped()) {
   960     _sp += nargs;          // gen_instanceof might do an uncommon trap
   961     Node* inst = gen_instanceof(argument, makecon(TypeKlassPtr::make(klass)));
   962     _sp -= nargs;
   963     Node* cmp  = _gvn.transform(new (C, 3) CmpINode(inst, intcon(1)));
   964     Node* bol  = _gvn.transform(new (C, 2) BoolNode(cmp, BoolTest::ne));
   966     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
   967     //instanceOf == true, fallthrough
   969     if (inst_false != NULL) {
   970       phi->init_req(3, intcon(0));
   971       region->init_req(3, inst_false);
   972     }
   973   }
   975   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
   977   Node* no_ctrl = NULL;
   978   Node* receiver_cnt;
   979   Node* argument_cnt;
   981   if (!stopped()) {
   982     // Properly cast the argument to String
   983     argument = _gvn.transform(new (C, 2) CheckCastPPNode(control(), argument, string_type));
   985     // Get counts for string and argument
   986     Node* receiver_cnta = basic_plus_adr(receiver, receiver, count_offset);
   987     receiver_cnt  = make_load(no_ctrl, receiver_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
   989     // Pin load from argument string since it could be NULL.
   990     Node* argument_cnta = basic_plus_adr(argument, argument, count_offset);
   991     argument_cnt  = make_load(control(), argument_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
   993     // Check for receiver count != argument count
   994     Node* cmp = _gvn.transform( new(C, 3) CmpINode(receiver_cnt, argument_cnt) );
   995     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::ne) );
   996     Node* if_ne = generate_slow_guard(bol, NULL);
   997     if (if_ne != NULL) {
   998       phi->init_req(4, intcon(0));
   999       region->init_req(4, if_ne);
  1003   // Check for count == 0 is done by mach node StrEquals.
  1005   if (!stopped()) {
  1006     Node* equals = make_string_method_node(Op_StrEquals, receiver, receiver_cnt, argument, argument_cnt);
  1007     phi->init_req(1, equals);
  1008     region->init_req(1, control());
  1011   // post merge
  1012   set_control(_gvn.transform(region));
  1013   record_for_igvn(region);
  1015   push(_gvn.transform(phi));
  1017   return true;
  1020 //------------------------------inline_array_equals----------------------------
  1021 bool LibraryCallKit::inline_array_equals() {
  1023   if (!Matcher::has_match_rule(Op_AryEq)) return false;
  1025   _sp += 2;
  1026   Node *argument2 = pop();
  1027   Node *argument1 = pop();
  1029   Node* equals =
  1030     _gvn.transform(new (C, 4) AryEqNode(control(), memory(TypeAryPtr::CHARS),
  1031                                         argument1, argument2) );
  1032   push(equals);
  1033   return true;
  1036 // Java version of String.indexOf(constant string)
  1037 // class StringDecl {
  1038 //   StringDecl(char[] ca) {
  1039 //     offset = 0;
  1040 //     count = ca.length;
  1041 //     value = ca;
  1042 //   }
  1043 //   int offset;
  1044 //   int count;
  1045 //   char[] value;
  1046 // }
  1047 //
  1048 // static int string_indexOf_J(StringDecl string_object, char[] target_object,
  1049 //                             int targetOffset, int cache_i, int md2) {
  1050 //   int cache = cache_i;
  1051 //   int sourceOffset = string_object.offset;
  1052 //   int sourceCount = string_object.count;
  1053 //   int targetCount = target_object.length;
  1054 //
  1055 //   int targetCountLess1 = targetCount - 1;
  1056 //   int sourceEnd = sourceOffset + sourceCount - targetCountLess1;
  1057 //
  1058 //   char[] source = string_object.value;
  1059 //   char[] target = target_object;
  1060 //   int lastChar = target[targetCountLess1];
  1061 //
  1062 //  outer_loop:
  1063 //   for (int i = sourceOffset; i < sourceEnd; ) {
  1064 //     int src = source[i + targetCountLess1];
  1065 //     if (src == lastChar) {
  1066 //       // With random strings and a 4-character alphabet,
  1067 //       // reverse matching at this point sets up 0.8% fewer
  1068 //       // frames, but (paradoxically) makes 0.3% more probes.
  1069 //       // Since those probes are nearer the lastChar probe,
  1070 //       // there is may be a net D$ win with reverse matching.
  1071 //       // But, reversing loop inhibits unroll of inner loop
  1072 //       // for unknown reason.  So, does running outer loop from
  1073 //       // (sourceOffset - targetCountLess1) to (sourceOffset + sourceCount)
  1074 //       for (int j = 0; j < targetCountLess1; j++) {
  1075 //         if (target[targetOffset + j] != source[i+j]) {
  1076 //           if ((cache & (1 << source[i+j])) == 0) {
  1077 //             if (md2 < j+1) {
  1078 //               i += j+1;
  1079 //               continue outer_loop;
  1080 //             }
  1081 //           }
  1082 //           i += md2;
  1083 //           continue outer_loop;
  1084 //         }
  1085 //       }
  1086 //       return i - sourceOffset;
  1087 //     }
  1088 //     if ((cache & (1 << src)) == 0) {
  1089 //       i += targetCountLess1;
  1090 //     } // using "i += targetCount;" and an "else i++;" causes a jump to jump.
  1091 //     i++;
  1092 //   }
  1093 //   return -1;
  1094 // }
  1096 //------------------------------string_indexOf------------------------
  1097 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
  1098                                      jint cache_i, jint md2_i) {
  1100   Node* no_ctrl  = NULL;
  1101   float likely   = PROB_LIKELY(0.9);
  1102   float unlikely = PROB_UNLIKELY(0.9);
  1104   const int nargs = 2; // number of arguments to push back for uncommon trap in predicate
  1106   const int value_offset  = java_lang_String::value_offset_in_bytes();
  1107   const int count_offset  = java_lang_String::count_offset_in_bytes();
  1108   const int offset_offset = java_lang_String::offset_offset_in_bytes();
  1110   ciInstanceKlass* klass = env()->String_klass();
  1111   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
  1112   const TypeAryPtr*  source_type = TypeAryPtr::make(TypePtr::NotNull, TypeAry::make(TypeInt::CHAR,TypeInt::POS), ciTypeArrayKlass::make(T_CHAR), true, 0);
  1114   Node* sourceOffseta = basic_plus_adr(string_object, string_object, offset_offset);
  1115   Node* sourceOffset  = make_load(no_ctrl, sourceOffseta, TypeInt::INT, T_INT, string_type->add_offset(offset_offset));
  1116   Node* sourceCounta  = basic_plus_adr(string_object, string_object, count_offset);
  1117   Node* sourceCount   = make_load(no_ctrl, sourceCounta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
  1118   Node* sourcea       = basic_plus_adr(string_object, string_object, value_offset);
  1119   Node* source        = make_load(no_ctrl, sourcea, source_type, T_OBJECT, string_type->add_offset(value_offset));
  1121   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)) );
  1122   jint target_length = target_array->length();
  1123   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
  1124   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
  1126   IdealKit kit(gvn(), control(), merged_memory(), false, true);
  1127 #define __ kit.
  1128   Node* zero             = __ ConI(0);
  1129   Node* one              = __ ConI(1);
  1130   Node* cache            = __ ConI(cache_i);
  1131   Node* md2              = __ ConI(md2_i);
  1132   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
  1133   Node* targetCount      = __ ConI(target_length);
  1134   Node* targetCountLess1 = __ ConI(target_length - 1);
  1135   Node* targetOffset     = __ ConI(targetOffset_i);
  1136   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
  1138   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
  1139   Node* outer_loop = __ make_label(2 /* goto */);
  1140   Node* return_    = __ make_label(1);
  1142   __ set(rtn,__ ConI(-1));
  1143   __ loop(this, nargs, i, sourceOffset, BoolTest::lt, sourceEnd); {
  1144        Node* i2  = __ AddI(__ value(i), targetCountLess1);
  1145        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
  1146        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
  1147        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
  1148          __ loop(this, nargs, j, zero, BoolTest::lt, targetCountLess1); {
  1149               Node* tpj = __ AddI(targetOffset, __ value(j));
  1150               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
  1151               Node* ipj  = __ AddI(__ value(i), __ value(j));
  1152               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
  1153               __ if_then(targ, BoolTest::ne, src2); {
  1154                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
  1155                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
  1156                     __ increment(i, __ AddI(__ value(j), one));
  1157                     __ goto_(outer_loop);
  1158                   } __ end_if(); __ dead(j);
  1159                 }__ end_if(); __ dead(j);
  1160                 __ increment(i, md2);
  1161                 __ goto_(outer_loop);
  1162               }__ end_if();
  1163               __ increment(j, one);
  1164          }__ end_loop(); __ dead(j);
  1165          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
  1166          __ goto_(return_);
  1167        }__ end_if();
  1168        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
  1169          __ increment(i, targetCountLess1);
  1170        }__ end_if();
  1171        __ increment(i, one);
  1172        __ bind(outer_loop);
  1173   }__ end_loop(); __ dead(i);
  1174   __ bind(return_);
  1176   // Final sync IdealKit and GraphKit.
  1177   sync_kit(kit);
  1178   Node* result = __ value(rtn);
  1179 #undef __
  1180   C->set_has_loops(true);
  1181   return result;
  1184 //------------------------------inline_string_indexOf------------------------
  1185 bool LibraryCallKit::inline_string_indexOf() {
  1187   const int value_offset  = java_lang_String::value_offset_in_bytes();
  1188   const int count_offset  = java_lang_String::count_offset_in_bytes();
  1189   const int offset_offset = java_lang_String::offset_offset_in_bytes();
  1191   _sp += 2;
  1192   Node *argument = pop();  // pop non-receiver first:  it was pushed second
  1193   Node *receiver = pop();
  1195   Node* result;
  1196   // Disable the use of pcmpestri until it can be guaranteed that
  1197   // the load doesn't cross into the uncommited space.
  1198   if (Matcher::has_match_rule(Op_StrIndexOf) &&
  1199       UseSSE42Intrinsics) {
  1200     // Generate SSE4.2 version of indexOf
  1201     // We currently only have match rules that use SSE4.2
  1203     // Null check on self without removing any arguments.  The argument
  1204     // null check technically happens in the wrong place, which can lead to
  1205     // invalid stack traces when string compare is inlined into a method
  1206     // which handles NullPointerExceptions.
  1207     _sp += 2;
  1208     receiver = do_null_check(receiver, T_OBJECT);
  1209     argument = do_null_check(argument, T_OBJECT);
  1210     _sp -= 2;
  1212     if (stopped()) {
  1213       return true;
  1216     ciInstanceKlass* str_klass = env()->String_klass();
  1217     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(str_klass);
  1219     // Make the merge point
  1220     RegionNode* result_rgn = new (C, 4) RegionNode(4);
  1221     Node*       result_phi = new (C, 4) PhiNode(result_rgn, TypeInt::INT);
  1222     Node* no_ctrl  = NULL;
  1224     // Get counts for string and substr
  1225     Node* source_cnta = basic_plus_adr(receiver, receiver, count_offset);
  1226     Node* source_cnt  = make_load(no_ctrl, source_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
  1228     Node* substr_cnta = basic_plus_adr(argument, argument, count_offset);
  1229     Node* substr_cnt  = make_load(no_ctrl, substr_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
  1231     // Check for substr count > string count
  1232     Node* cmp = _gvn.transform( new(C, 3) CmpINode(substr_cnt, source_cnt) );
  1233     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::gt) );
  1234     Node* if_gt = generate_slow_guard(bol, NULL);
  1235     if (if_gt != NULL) {
  1236       result_phi->init_req(2, intcon(-1));
  1237       result_rgn->init_req(2, if_gt);
  1240     if (!stopped()) {
  1241       // Check for substr count == 0
  1242       cmp = _gvn.transform( new(C, 3) CmpINode(substr_cnt, intcon(0)) );
  1243       bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::eq) );
  1244       Node* if_zero = generate_slow_guard(bol, NULL);
  1245       if (if_zero != NULL) {
  1246         result_phi->init_req(3, intcon(0));
  1247         result_rgn->init_req(3, if_zero);
  1251     if (!stopped()) {
  1252       result = make_string_method_node(Op_StrIndexOf, receiver, source_cnt, argument, substr_cnt);
  1253       result_phi->init_req(1, result);
  1254       result_rgn->init_req(1, control());
  1256     set_control(_gvn.transform(result_rgn));
  1257     record_for_igvn(result_rgn);
  1258     result = _gvn.transform(result_phi);
  1260   } else { // Use LibraryCallKit::string_indexOf
  1261     // don't intrinsify if argument isn't a constant string.
  1262     if (!argument->is_Con()) {
  1263      return false;
  1265     const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
  1266     if (str_type == NULL) {
  1267       return false;
  1269     ciInstanceKlass* klass = env()->String_klass();
  1270     ciObject* str_const = str_type->const_oop();
  1271     if (str_const == NULL || str_const->klass() != klass) {
  1272       return false;
  1274     ciInstance* str = str_const->as_instance();
  1275     assert(str != NULL, "must be instance");
  1277     ciObject* v = str->field_value_by_offset(value_offset).as_object();
  1278     int       o = str->field_value_by_offset(offset_offset).as_int();
  1279     int       c = str->field_value_by_offset(count_offset).as_int();
  1280     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
  1282     // constant strings have no offset and count == length which
  1283     // simplifies the resulting code somewhat so lets optimize for that.
  1284     if (o != 0 || c != pat->length()) {
  1285      return false;
  1288     // Null check on self without removing any arguments.  The argument
  1289     // null check technically happens in the wrong place, which can lead to
  1290     // invalid stack traces when string compare is inlined into a method
  1291     // which handles NullPointerExceptions.
  1292     _sp += 2;
  1293     receiver = do_null_check(receiver, T_OBJECT);
  1294     // No null check on the argument is needed since it's a constant String oop.
  1295     _sp -= 2;
  1296     if (stopped()) {
  1297       return true;
  1300     // The null string as a pattern always returns 0 (match at beginning of string)
  1301     if (c == 0) {
  1302       push(intcon(0));
  1303       return true;
  1306     // Generate default indexOf
  1307     jchar lastChar = pat->char_at(o + (c - 1));
  1308     int cache = 0;
  1309     int i;
  1310     for (i = 0; i < c - 1; i++) {
  1311       assert(i < pat->length(), "out of range");
  1312       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
  1315     int md2 = c;
  1316     for (i = 0; i < c - 1; i++) {
  1317       assert(i < pat->length(), "out of range");
  1318       if (pat->char_at(o + i) == lastChar) {
  1319         md2 = (c - 1) - i;
  1323     result = string_indexOf(receiver, pat, o, cache, md2);
  1326   push(result);
  1327   return true;
  1330 //--------------------------pop_math_arg--------------------------------
  1331 // Pop a double argument to a math function from the stack
  1332 // rounding it if necessary.
  1333 Node * LibraryCallKit::pop_math_arg() {
  1334   Node *arg = pop_pair();
  1335   if( Matcher::strict_fp_requires_explicit_rounding && UseSSE<=1 )
  1336     arg = _gvn.transform( new (C, 2) RoundDoubleNode(0, arg) );
  1337   return arg;
  1340 //------------------------------inline_trig----------------------------------
  1341 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
  1342 // argument reduction which will turn into a fast/slow diamond.
  1343 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
  1344   _sp += arg_size();            // restore stack pointer
  1345   Node* arg = pop_math_arg();
  1346   Node* trig = NULL;
  1348   switch (id) {
  1349   case vmIntrinsics::_dsin:
  1350     trig = _gvn.transform((Node*)new (C, 2) SinDNode(arg));
  1351     break;
  1352   case vmIntrinsics::_dcos:
  1353     trig = _gvn.transform((Node*)new (C, 2) CosDNode(arg));
  1354     break;
  1355   case vmIntrinsics::_dtan:
  1356     trig = _gvn.transform((Node*)new (C, 2) TanDNode(arg));
  1357     break;
  1358   default:
  1359     assert(false, "bad intrinsic was passed in");
  1360     return false;
  1363   // Rounding required?  Check for argument reduction!
  1364   if( Matcher::strict_fp_requires_explicit_rounding ) {
  1366     static const double     pi_4 =  0.7853981633974483;
  1367     static const double neg_pi_4 = -0.7853981633974483;
  1368     // pi/2 in 80-bit extended precision
  1369     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
  1370     // -pi/2 in 80-bit extended precision
  1371     // 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};
  1372     // Cutoff value for using this argument reduction technique
  1373     //static const double    pi_2_minus_epsilon =  1.564660403643354;
  1374     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
  1376     // Pseudocode for sin:
  1377     // if (x <= Math.PI / 4.0) {
  1378     //   if (x >= -Math.PI / 4.0) return  fsin(x);
  1379     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
  1380     // } else {
  1381     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
  1382     // }
  1383     // return StrictMath.sin(x);
  1385     // Pseudocode for cos:
  1386     // if (x <= Math.PI / 4.0) {
  1387     //   if (x >= -Math.PI / 4.0) return  fcos(x);
  1388     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
  1389     // } else {
  1390     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
  1391     // }
  1392     // return StrictMath.cos(x);
  1394     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
  1395     // requires a special machine instruction to load it.  Instead we'll try
  1396     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
  1397     // probably do the math inside the SIN encoding.
  1399     // Make the merge point
  1400     RegionNode *r = new (C, 3) RegionNode(3);
  1401     Node *phi = new (C, 3) PhiNode(r,Type::DOUBLE);
  1403     // Flatten arg so we need only 1 test
  1404     Node *abs = _gvn.transform(new (C, 2) AbsDNode(arg));
  1405     // Node for PI/4 constant
  1406     Node *pi4 = makecon(TypeD::make(pi_4));
  1407     // Check PI/4 : abs(arg)
  1408     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(pi4,abs));
  1409     // Check: If PI/4 < abs(arg) then go slow
  1410     Node *bol = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::lt ) );
  1411     // Branch either way
  1412     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  1413     set_control(opt_iff(r,iff));
  1415     // Set fast path result
  1416     phi->init_req(2,trig);
  1418     // Slow path - non-blocking leaf call
  1419     Node* call = NULL;
  1420     switch (id) {
  1421     case vmIntrinsics::_dsin:
  1422       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1423                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
  1424                                "Sin", NULL, arg, top());
  1425       break;
  1426     case vmIntrinsics::_dcos:
  1427       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1428                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
  1429                                "Cos", NULL, arg, top());
  1430       break;
  1431     case vmIntrinsics::_dtan:
  1432       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
  1433                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
  1434                                "Tan", NULL, arg, top());
  1435       break;
  1437     assert(control()->in(0) == call, "");
  1438     Node* slow_result = _gvn.transform(new (C, 1) ProjNode(call,TypeFunc::Parms));
  1439     r->init_req(1,control());
  1440     phi->init_req(1,slow_result);
  1442     // Post-merge
  1443     set_control(_gvn.transform(r));
  1444     record_for_igvn(r);
  1445     trig = _gvn.transform(phi);
  1447     C->set_has_split_ifs(true); // Has chance for split-if optimization
  1449   // Push result back on JVM stack
  1450   push_pair(trig);
  1451   return true;
  1454 //------------------------------inline_sqrt-------------------------------------
  1455 // Inline square root instruction, if possible.
  1456 bool LibraryCallKit::inline_sqrt(vmIntrinsics::ID id) {
  1457   assert(id == vmIntrinsics::_dsqrt, "Not square root");
  1458   _sp += arg_size();        // restore stack pointer
  1459   push_pair(_gvn.transform(new (C, 2) SqrtDNode(0, pop_math_arg())));
  1460   return true;
  1463 //------------------------------inline_abs-------------------------------------
  1464 // Inline absolute value instruction, if possible.
  1465 bool LibraryCallKit::inline_abs(vmIntrinsics::ID id) {
  1466   assert(id == vmIntrinsics::_dabs, "Not absolute value");
  1467   _sp += arg_size();        // restore stack pointer
  1468   push_pair(_gvn.transform(new (C, 2) AbsDNode(pop_math_arg())));
  1469   return true;
  1472 //------------------------------inline_exp-------------------------------------
  1473 // Inline exp instructions, if possible.  The Intel hardware only misses
  1474 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
  1475 bool LibraryCallKit::inline_exp(vmIntrinsics::ID id) {
  1476   assert(id == vmIntrinsics::_dexp, "Not exp");
  1478   // If this inlining ever returned NaN in the past, we do not intrinsify it
  1479   // every again.  NaN results requires StrictMath.exp handling.
  1480   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  1482   // Do not intrinsify on older platforms which lack cmove.
  1483   if (ConditionalMoveLimit == 0)  return false;
  1485   _sp += arg_size();        // restore stack pointer
  1486   Node *x = pop_math_arg();
  1487   Node *result = _gvn.transform(new (C, 2) ExpDNode(0,x));
  1489   //-------------------
  1490   //result=(result.isNaN())? StrictMath::exp():result;
  1491   // Check: If isNaN() by checking result!=result? then go to Strict Math
  1492   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
  1493   // Build the boolean node
  1494   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
  1496   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
  1497     // End the current control-flow path
  1498     push_pair(x);
  1499     // Math.exp intrinsic returned a NaN, which requires StrictMath.exp
  1500     // to handle.  Recompile without intrinsifying Math.exp
  1501     uncommon_trap(Deoptimization::Reason_intrinsic,
  1502                   Deoptimization::Action_make_not_entrant);
  1505   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1507   push_pair(result);
  1509   return true;
  1512 //------------------------------inline_pow-------------------------------------
  1513 // Inline power instructions, if possible.
  1514 bool LibraryCallKit::inline_pow(vmIntrinsics::ID id) {
  1515   assert(id == vmIntrinsics::_dpow, "Not pow");
  1517   // If this inlining ever returned NaN in the past, we do not intrinsify it
  1518   // every again.  NaN results requires StrictMath.pow handling.
  1519   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  1521   // Do not intrinsify on older platforms which lack cmove.
  1522   if (ConditionalMoveLimit == 0)  return false;
  1524   // Pseudocode for pow
  1525   // if (x <= 0.0) {
  1526   //   if ((double)((int)y)==y) { // if y is int
  1527   //     result = ((1&(int)y)==0)?-DPow(abs(x), y):DPow(abs(x), y)
  1528   //   } else {
  1529   //     result = NaN;
  1530   //   }
  1531   // } else {
  1532   //   result = DPow(x,y);
  1533   // }
  1534   // if (result != result)?  {
  1535   //   uncommon_trap();
  1536   // }
  1537   // return result;
  1539   _sp += arg_size();        // restore stack pointer
  1540   Node* y = pop_math_arg();
  1541   Node* x = pop_math_arg();
  1543   Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, x, y) );
  1545   // Short form: if not top-level (i.e., Math.pow but inlining Math.pow
  1546   // inside of something) then skip the fancy tests and just check for
  1547   // NaN result.
  1548   Node *result = NULL;
  1549   if( jvms()->depth() >= 1 ) {
  1550     result = fast_result;
  1551   } else {
  1553     // Set the merge point for If node with condition of (x <= 0.0)
  1554     // There are four possible paths to region node and phi node
  1555     RegionNode *r = new (C, 4) RegionNode(4);
  1556     Node *phi = new (C, 4) PhiNode(r, Type::DOUBLE);
  1558     // Build the first if node: if (x <= 0.0)
  1559     // Node for 0 constant
  1560     Node *zeronode = makecon(TypeD::ZERO);
  1561     // Check x:0
  1562     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(x, zeronode));
  1563     // Check: If (x<=0) then go complex path
  1564     Node *bol1 = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::le ) );
  1565     // Branch either way
  1566     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1567     Node *opt_test = _gvn.transform(if1);
  1568     //assert( opt_test->is_If(), "Expect an IfNode");
  1569     IfNode *opt_if1 = (IfNode*)opt_test;
  1570     // Fast path taken; set region slot 3
  1571     Node *fast_taken = _gvn.transform( new (C, 1) IfFalseNode(opt_if1) );
  1572     r->init_req(3,fast_taken); // Capture fast-control
  1574     // Fast path not-taken, i.e. slow path
  1575     Node *complex_path = _gvn.transform( new (C, 1) IfTrueNode(opt_if1) );
  1577     // Set fast path result
  1578     Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, y, x) );
  1579     phi->init_req(3, fast_result);
  1581     // Complex path
  1582     // Build the second if node (if y is int)
  1583     // Node for (int)y
  1584     Node *inty = _gvn.transform( new (C, 2) ConvD2INode(y));
  1585     // Node for (double)((int) y)
  1586     Node *doubleinty= _gvn.transform( new (C, 2) ConvI2DNode(inty));
  1587     // Check (double)((int) y) : y
  1588     Node *cmpinty= _gvn.transform(new (C, 3) CmpDNode(doubleinty, y));
  1589     // Check if (y isn't int) then go to slow path
  1591     Node *bol2 = _gvn.transform( new (C, 2) BoolNode( cmpinty, BoolTest::ne ) );
  1592     // Branch either way
  1593     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
  1594     Node *slow_path = opt_iff(r,if2); // Set region path 2
  1596     // Calculate DPow(abs(x), y)*(1 & (int)y)
  1597     // Node for constant 1
  1598     Node *conone = intcon(1);
  1599     // 1& (int)y
  1600     Node *signnode= _gvn.transform( new (C, 3) AndINode(conone, inty) );
  1601     // zero node
  1602     Node *conzero = intcon(0);
  1603     // Check (1&(int)y)==0?
  1604     Node *cmpeq1 = _gvn.transform(new (C, 3) CmpINode(signnode, conzero));
  1605     // Check if (1&(int)y)!=0?, if so the result is negative
  1606     Node *bol3 = _gvn.transform( new (C, 2) BoolNode( cmpeq1, BoolTest::ne ) );
  1607     // abs(x)
  1608     Node *absx=_gvn.transform( new (C, 2) AbsDNode(x));
  1609     // abs(x)^y
  1610     Node *absxpowy = _gvn.transform( new (C, 3) PowDNode(0, y, absx) );
  1611     // -abs(x)^y
  1612     Node *negabsxpowy = _gvn.transform(new (C, 2) NegDNode (absxpowy));
  1613     // (1&(int)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
  1614     Node *signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
  1615     // Set complex path fast result
  1616     phi->init_req(2, signresult);
  1618     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  1619     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
  1620     r->init_req(1,slow_path);
  1621     phi->init_req(1,slow_result);
  1623     // Post merge
  1624     set_control(_gvn.transform(r));
  1625     record_for_igvn(r);
  1626     result=_gvn.transform(phi);
  1629   //-------------------
  1630   //result=(result.isNaN())? uncommon_trap():result;
  1631   // Check: If isNaN() by checking result!=result? then go to Strict Math
  1632   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
  1633   // Build the boolean node
  1634   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
  1636   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
  1637     // End the current control-flow path
  1638     push_pair(x);
  1639     push_pair(y);
  1640     // Math.pow intrinsic returned a NaN, which requires StrictMath.pow
  1641     // to handle.  Recompile without intrinsifying Math.pow.
  1642     uncommon_trap(Deoptimization::Reason_intrinsic,
  1643                   Deoptimization::Action_make_not_entrant);
  1646   C->set_has_split_ifs(true); // Has chance for split-if optimization
  1648   push_pair(result);
  1650   return true;
  1653 //------------------------------inline_trans-------------------------------------
  1654 // Inline transcendental instructions, if possible.  The Intel hardware gets
  1655 // these right, no funny corner cases missed.
  1656 bool LibraryCallKit::inline_trans(vmIntrinsics::ID id) {
  1657   _sp += arg_size();        // restore stack pointer
  1658   Node* arg = pop_math_arg();
  1659   Node* trans = NULL;
  1661   switch (id) {
  1662   case vmIntrinsics::_dlog:
  1663     trans = _gvn.transform((Node*)new (C, 2) LogDNode(arg));
  1664     break;
  1665   case vmIntrinsics::_dlog10:
  1666     trans = _gvn.transform((Node*)new (C, 2) Log10DNode(arg));
  1667     break;
  1668   default:
  1669     assert(false, "bad intrinsic was passed in");
  1670     return false;
  1673   // Push result back on JVM stack
  1674   push_pair(trans);
  1675   return true;
  1678 //------------------------------runtime_math-----------------------------
  1679 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
  1680   Node* a = NULL;
  1681   Node* b = NULL;
  1683   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
  1684          "must be (DD)D or (D)D type");
  1686   // Inputs
  1687   _sp += arg_size();        // restore stack pointer
  1688   if (call_type == OptoRuntime::Math_DD_D_Type()) {
  1689     b = pop_math_arg();
  1691   a = pop_math_arg();
  1693   const TypePtr* no_memory_effects = NULL;
  1694   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
  1695                                  no_memory_effects,
  1696                                  a, top(), b, b ? top() : NULL);
  1697   Node* value = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+0));
  1698 #ifdef ASSERT
  1699   Node* value_top = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+1));
  1700   assert(value_top == top(), "second value must be top");
  1701 #endif
  1703   push_pair(value);
  1704   return true;
  1707 //------------------------------inline_math_native-----------------------------
  1708 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
  1709   switch (id) {
  1710     // These intrinsics are not properly supported on all hardware
  1711   case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :
  1712     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
  1713   case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :
  1714     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
  1715   case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :
  1716     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
  1718   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD) ? inline_trans(id) :
  1719     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
  1720   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_trans(id) :
  1721     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
  1723     // These intrinsics are supported on all hardware
  1724   case vmIntrinsics::_dsqrt: return Matcher::has_match_rule(Op_SqrtD) ? inline_sqrt(id) : false;
  1725   case vmIntrinsics::_dabs:  return Matcher::has_match_rule(Op_AbsD)  ? inline_abs(id)  : false;
  1727     // These intrinsics don't work on X86.  The ad implementation doesn't
  1728     // handle NaN's properly.  Instead of returning infinity, the ad
  1729     // implementation returns a NaN on overflow. See bug: 6304089
  1730     // Once the ad implementations are fixed, change the code below
  1731     // to match the intrinsics above
  1733   case vmIntrinsics::_dexp:  return
  1734     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
  1735   case vmIntrinsics::_dpow:  return
  1736     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
  1738    // These intrinsics are not yet correctly implemented
  1739   case vmIntrinsics::_datan2:
  1740     return false;
  1742   default:
  1743     ShouldNotReachHere();
  1744     return false;
  1748 static bool is_simple_name(Node* n) {
  1749   return (n->req() == 1         // constant
  1750           || (n->is_Type() && n->as_Type()->type()->singleton())
  1751           || n->is_Proj()       // parameter or return value
  1752           || n->is_Phi()        // local of some sort
  1753           );
  1756 //----------------------------inline_min_max-----------------------------------
  1757 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
  1758   push(generate_min_max(id, argument(0), argument(1)));
  1760   return true;
  1763 Node*
  1764 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
  1765   // These are the candidate return value:
  1766   Node* xvalue = x0;
  1767   Node* yvalue = y0;
  1769   if (xvalue == yvalue) {
  1770     return xvalue;
  1773   bool want_max = (id == vmIntrinsics::_max);
  1775   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
  1776   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
  1777   if (txvalue == NULL || tyvalue == NULL)  return top();
  1778   // This is not really necessary, but it is consistent with a
  1779   // hypothetical MaxINode::Value method:
  1780   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
  1782   // %%% This folding logic should (ideally) be in a different place.
  1783   // Some should be inside IfNode, and there to be a more reliable
  1784   // transformation of ?: style patterns into cmoves.  We also want
  1785   // more powerful optimizations around cmove and min/max.
  1787   // Try to find a dominating comparison of these guys.
  1788   // It can simplify the index computation for Arrays.copyOf
  1789   // and similar uses of System.arraycopy.
  1790   // First, compute the normalized version of CmpI(x, y).
  1791   int   cmp_op = Op_CmpI;
  1792   Node* xkey = xvalue;
  1793   Node* ykey = yvalue;
  1794   Node* ideal_cmpxy = _gvn.transform( new(C, 3) CmpINode(xkey, ykey) );
  1795   if (ideal_cmpxy->is_Cmp()) {
  1796     // E.g., if we have CmpI(length - offset, count),
  1797     // it might idealize to CmpI(length, count + offset)
  1798     cmp_op = ideal_cmpxy->Opcode();
  1799     xkey = ideal_cmpxy->in(1);
  1800     ykey = ideal_cmpxy->in(2);
  1803   // Start by locating any relevant comparisons.
  1804   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
  1805   Node* cmpxy = NULL;
  1806   Node* cmpyx = NULL;
  1807   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
  1808     Node* cmp = start_from->fast_out(k);
  1809     if (cmp->outcnt() > 0 &&            // must have prior uses
  1810         cmp->in(0) == NULL &&           // must be context-independent
  1811         cmp->Opcode() == cmp_op) {      // right kind of compare
  1812       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
  1813       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
  1817   const int NCMPS = 2;
  1818   Node* cmps[NCMPS] = { cmpxy, cmpyx };
  1819   int cmpn;
  1820   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  1821     if (cmps[cmpn] != NULL)  break;     // find a result
  1823   if (cmpn < NCMPS) {
  1824     // Look for a dominating test that tells us the min and max.
  1825     int depth = 0;                // Limit search depth for speed
  1826     Node* dom = control();
  1827     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
  1828       if (++depth >= 100)  break;
  1829       Node* ifproj = dom;
  1830       if (!ifproj->is_Proj())  continue;
  1831       Node* iff = ifproj->in(0);
  1832       if (!iff->is_If())  continue;
  1833       Node* bol = iff->in(1);
  1834       if (!bol->is_Bool())  continue;
  1835       Node* cmp = bol->in(1);
  1836       if (cmp == NULL)  continue;
  1837       for (cmpn = 0; cmpn < NCMPS; cmpn++)
  1838         if (cmps[cmpn] == cmp)  break;
  1839       if (cmpn == NCMPS)  continue;
  1840       BoolTest::mask btest = bol->as_Bool()->_test._test;
  1841       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
  1842       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
  1843       // At this point, we know that 'x btest y' is true.
  1844       switch (btest) {
  1845       case BoolTest::eq:
  1846         // They are proven equal, so we can collapse the min/max.
  1847         // Either value is the answer.  Choose the simpler.
  1848         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
  1849           return yvalue;
  1850         return xvalue;
  1851       case BoolTest::lt:          // x < y
  1852       case BoolTest::le:          // x <= y
  1853         return (want_max ? yvalue : xvalue);
  1854       case BoolTest::gt:          // x > y
  1855       case BoolTest::ge:          // x >= y
  1856         return (want_max ? xvalue : yvalue);
  1861   // We failed to find a dominating test.
  1862   // Let's pick a test that might GVN with prior tests.
  1863   Node*          best_bol   = NULL;
  1864   BoolTest::mask best_btest = BoolTest::illegal;
  1865   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
  1866     Node* cmp = cmps[cmpn];
  1867     if (cmp == NULL)  continue;
  1868     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
  1869       Node* bol = cmp->fast_out(j);
  1870       if (!bol->is_Bool())  continue;
  1871       BoolTest::mask btest = bol->as_Bool()->_test._test;
  1872       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
  1873       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
  1874       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
  1875         best_bol   = bol->as_Bool();
  1876         best_btest = btest;
  1881   Node* answer_if_true  = NULL;
  1882   Node* answer_if_false = NULL;
  1883   switch (best_btest) {
  1884   default:
  1885     if (cmpxy == NULL)
  1886       cmpxy = ideal_cmpxy;
  1887     best_bol = _gvn.transform( new(C, 2) BoolNode(cmpxy, BoolTest::lt) );
  1888     // and fall through:
  1889   case BoolTest::lt:          // x < y
  1890   case BoolTest::le:          // x <= y
  1891     answer_if_true  = (want_max ? yvalue : xvalue);
  1892     answer_if_false = (want_max ? xvalue : yvalue);
  1893     break;
  1894   case BoolTest::gt:          // x > y
  1895   case BoolTest::ge:          // x >= y
  1896     answer_if_true  = (want_max ? xvalue : yvalue);
  1897     answer_if_false = (want_max ? yvalue : xvalue);
  1898     break;
  1901   jint hi, lo;
  1902   if (want_max) {
  1903     // We can sharpen the minimum.
  1904     hi = MAX2(txvalue->_hi, tyvalue->_hi);
  1905     lo = MAX2(txvalue->_lo, tyvalue->_lo);
  1906   } else {
  1907     // We can sharpen the maximum.
  1908     hi = MIN2(txvalue->_hi, tyvalue->_hi);
  1909     lo = MIN2(txvalue->_lo, tyvalue->_lo);
  1912   // Use a flow-free graph structure, to avoid creating excess control edges
  1913   // which could hinder other optimizations.
  1914   // Since Math.min/max is often used with arraycopy, we want
  1915   // tightly_coupled_allocation to be able to see beyond min/max expressions.
  1916   Node* cmov = CMoveNode::make(C, NULL, best_bol,
  1917                                answer_if_false, answer_if_true,
  1918                                TypeInt::make(lo, hi, widen));
  1920   return _gvn.transform(cmov);
  1922   /*
  1923   // This is not as desirable as it may seem, since Min and Max
  1924   // nodes do not have a full set of optimizations.
  1925   // And they would interfere, anyway, with 'if' optimizations
  1926   // and with CMoveI canonical forms.
  1927   switch (id) {
  1928   case vmIntrinsics::_min:
  1929     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
  1930   case vmIntrinsics::_max:
  1931     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
  1932   default:
  1933     ShouldNotReachHere();
  1935   */
  1938 inline int
  1939 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
  1940   const TypePtr* base_type = TypePtr::NULL_PTR;
  1941   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
  1942   if (base_type == NULL) {
  1943     // Unknown type.
  1944     return Type::AnyPtr;
  1945   } else if (base_type == TypePtr::NULL_PTR) {
  1946     // Since this is a NULL+long form, we have to switch to a rawptr.
  1947     base   = _gvn.transform( new (C, 2) CastX2PNode(offset) );
  1948     offset = MakeConX(0);
  1949     return Type::RawPtr;
  1950   } else if (base_type->base() == Type::RawPtr) {
  1951     return Type::RawPtr;
  1952   } else if (base_type->isa_oopptr()) {
  1953     // Base is never null => always a heap address.
  1954     if (base_type->ptr() == TypePtr::NotNull) {
  1955       return Type::OopPtr;
  1957     // Offset is small => always a heap address.
  1958     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
  1959     if (offset_type != NULL &&
  1960         base_type->offset() == 0 &&     // (should always be?)
  1961         offset_type->_lo >= 0 &&
  1962         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
  1963       return Type::OopPtr;
  1965     // Otherwise, it might either be oop+off or NULL+addr.
  1966     return Type::AnyPtr;
  1967   } else {
  1968     // No information:
  1969     return Type::AnyPtr;
  1973 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
  1974   int kind = classify_unsafe_addr(base, offset);
  1975   if (kind == Type::RawPtr) {
  1976     return basic_plus_adr(top(), base, offset);
  1977   } else {
  1978     return basic_plus_adr(base, offset);
  1982 //-------------------inline_numberOfLeadingZeros_int/long-----------------------
  1983 // inline int Integer.numberOfLeadingZeros(int)
  1984 // inline int Long.numberOfLeadingZeros(long)
  1985 bool LibraryCallKit::inline_numberOfLeadingZeros(vmIntrinsics::ID id) {
  1986   assert(id == vmIntrinsics::_numberOfLeadingZeros_i || id == vmIntrinsics::_numberOfLeadingZeros_l, "not numberOfLeadingZeros");
  1987   if (id == vmIntrinsics::_numberOfLeadingZeros_i && !Matcher::match_rule_supported(Op_CountLeadingZerosI)) return false;
  1988   if (id == vmIntrinsics::_numberOfLeadingZeros_l && !Matcher::match_rule_supported(Op_CountLeadingZerosL)) return false;
  1989   _sp += arg_size();  // restore stack pointer
  1990   switch (id) {
  1991   case vmIntrinsics::_numberOfLeadingZeros_i:
  1992     push(_gvn.transform(new (C, 2) CountLeadingZerosINode(pop())));
  1993     break;
  1994   case vmIntrinsics::_numberOfLeadingZeros_l:
  1995     push(_gvn.transform(new (C, 2) CountLeadingZerosLNode(pop_pair())));
  1996     break;
  1997   default:
  1998     ShouldNotReachHere();
  2000   return true;
  2003 //-------------------inline_numberOfTrailingZeros_int/long----------------------
  2004 // inline int Integer.numberOfTrailingZeros(int)
  2005 // inline int Long.numberOfTrailingZeros(long)
  2006 bool LibraryCallKit::inline_numberOfTrailingZeros(vmIntrinsics::ID id) {
  2007   assert(id == vmIntrinsics::_numberOfTrailingZeros_i || id == vmIntrinsics::_numberOfTrailingZeros_l, "not numberOfTrailingZeros");
  2008   if (id == vmIntrinsics::_numberOfTrailingZeros_i && !Matcher::match_rule_supported(Op_CountTrailingZerosI)) return false;
  2009   if (id == vmIntrinsics::_numberOfTrailingZeros_l && !Matcher::match_rule_supported(Op_CountTrailingZerosL)) return false;
  2010   _sp += arg_size();  // restore stack pointer
  2011   switch (id) {
  2012   case vmIntrinsics::_numberOfTrailingZeros_i:
  2013     push(_gvn.transform(new (C, 2) CountTrailingZerosINode(pop())));
  2014     break;
  2015   case vmIntrinsics::_numberOfTrailingZeros_l:
  2016     push(_gvn.transform(new (C, 2) CountTrailingZerosLNode(pop_pair())));
  2017     break;
  2018   default:
  2019     ShouldNotReachHere();
  2021   return true;
  2024 //----------------------------inline_bitCount_int/long-----------------------
  2025 // inline int Integer.bitCount(int)
  2026 // inline int Long.bitCount(long)
  2027 bool LibraryCallKit::inline_bitCount(vmIntrinsics::ID id) {
  2028   assert(id == vmIntrinsics::_bitCount_i || id == vmIntrinsics::_bitCount_l, "not bitCount");
  2029   if (id == vmIntrinsics::_bitCount_i && !Matcher::has_match_rule(Op_PopCountI)) return false;
  2030   if (id == vmIntrinsics::_bitCount_l && !Matcher::has_match_rule(Op_PopCountL)) return false;
  2031   _sp += arg_size();  // restore stack pointer
  2032   switch (id) {
  2033   case vmIntrinsics::_bitCount_i:
  2034     push(_gvn.transform(new (C, 2) PopCountINode(pop())));
  2035     break;
  2036   case vmIntrinsics::_bitCount_l:
  2037     push(_gvn.transform(new (C, 2) PopCountLNode(pop_pair())));
  2038     break;
  2039   default:
  2040     ShouldNotReachHere();
  2042   return true;
  2045 //----------------------------inline_reverseBytes_int/long/char/short-------------------
  2046 // inline Integer.reverseBytes(int)
  2047 // inline Long.reverseBytes(long)
  2048 // inline Character.reverseBytes(char)
  2049 // inline Short.reverseBytes(short)
  2050 bool LibraryCallKit::inline_reverseBytes(vmIntrinsics::ID id) {
  2051   assert(id == vmIntrinsics::_reverseBytes_i || id == vmIntrinsics::_reverseBytes_l ||
  2052          id == vmIntrinsics::_reverseBytes_c || id == vmIntrinsics::_reverseBytes_s,
  2053          "not reverse Bytes");
  2054   if (id == vmIntrinsics::_reverseBytes_i && !Matcher::has_match_rule(Op_ReverseBytesI))  return false;
  2055   if (id == vmIntrinsics::_reverseBytes_l && !Matcher::has_match_rule(Op_ReverseBytesL))  return false;
  2056   if (id == vmIntrinsics::_reverseBytes_c && !Matcher::has_match_rule(Op_ReverseBytesUS)) return false;
  2057   if (id == vmIntrinsics::_reverseBytes_s && !Matcher::has_match_rule(Op_ReverseBytesS))  return false;
  2058   _sp += arg_size();        // restore stack pointer
  2059   switch (id) {
  2060   case vmIntrinsics::_reverseBytes_i:
  2061     push(_gvn.transform(new (C, 2) ReverseBytesINode(0, pop())));
  2062     break;
  2063   case vmIntrinsics::_reverseBytes_l:
  2064     push_pair(_gvn.transform(new (C, 2) ReverseBytesLNode(0, pop_pair())));
  2065     break;
  2066   case vmIntrinsics::_reverseBytes_c:
  2067     push(_gvn.transform(new (C, 2) ReverseBytesUSNode(0, pop())));
  2068     break;
  2069   case vmIntrinsics::_reverseBytes_s:
  2070     push(_gvn.transform(new (C, 2) ReverseBytesSNode(0, pop())));
  2071     break;
  2072   default:
  2075   return true;
  2078 //----------------------------inline_unsafe_access----------------------------
  2080 const static BasicType T_ADDRESS_HOLDER = T_LONG;
  2082 // Interpret Unsafe.fieldOffset cookies correctly:
  2083 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
  2085 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
  2086   if (callee()->is_static())  return false;  // caller must have the capability!
  2088 #ifndef PRODUCT
  2090     ResourceMark rm;
  2091     // Check the signatures.
  2092     ciSignature* sig = signature();
  2093 #ifdef ASSERT
  2094     if (!is_store) {
  2095       // Object getObject(Object base, int/long offset), etc.
  2096       BasicType rtype = sig->return_type()->basic_type();
  2097       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
  2098           rtype = T_ADDRESS;  // it is really a C void*
  2099       assert(rtype == type, "getter must return the expected value");
  2100       if (!is_native_ptr) {
  2101         assert(sig->count() == 2, "oop getter has 2 arguments");
  2102         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
  2103         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
  2104       } else {
  2105         assert(sig->count() == 1, "native getter has 1 argument");
  2106         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
  2108     } else {
  2109       // void putObject(Object base, int/long offset, Object x), etc.
  2110       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
  2111       if (!is_native_ptr) {
  2112         assert(sig->count() == 3, "oop putter has 3 arguments");
  2113         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
  2114         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
  2115       } else {
  2116         assert(sig->count() == 2, "native putter has 2 arguments");
  2117         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
  2119       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
  2120       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
  2121         vtype = T_ADDRESS;  // it is really a C void*
  2122       assert(vtype == type, "putter must accept the expected value");
  2124 #endif // ASSERT
  2126 #endif //PRODUCT
  2128   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2130   int type_words = type2size[ (type == T_ADDRESS) ? T_LONG : type ];
  2132   // Argument words:  "this" plus (oop/offset) or (lo/hi) args plus maybe 1 or 2 value words
  2133   int nargs = 1 + (is_native_ptr ? 2 : 3) + (is_store ? type_words : 0);
  2135   debug_only(int saved_sp = _sp);
  2136   _sp += nargs;
  2138   Node* val;
  2139   debug_only(val = (Node*)(uintptr_t)-1);
  2142   if (is_store) {
  2143     // Get the value being stored.  (Pop it first; it was pushed last.)
  2144     switch (type) {
  2145     case T_DOUBLE:
  2146     case T_LONG:
  2147     case T_ADDRESS:
  2148       val = pop_pair();
  2149       break;
  2150     default:
  2151       val = pop();
  2155   // Build address expression.  See the code in inline_unsafe_prefetch.
  2156   Node *adr;
  2157   Node *heap_base_oop = top();
  2158   if (!is_native_ptr) {
  2159     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2160     Node* offset = pop_pair();
  2161     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2162     Node* base   = pop();
  2163     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2164     // to be plain byte offsets, which are also the same as those accepted
  2165     // by oopDesc::field_base.
  2166     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2167            "fieldOffset must be byte-scaled");
  2168     // 32-bit machines ignore the high half!
  2169     offset = ConvL2X(offset);
  2170     adr = make_unsafe_address(base, offset);
  2171     heap_base_oop = base;
  2172   } else {
  2173     Node* ptr = pop_pair();
  2174     // Adjust Java long to machine word:
  2175     ptr = ConvL2X(ptr);
  2176     adr = make_unsafe_address(NULL, ptr);
  2179   // Pop receiver last:  it was pushed first.
  2180   Node *receiver = pop();
  2182   assert(saved_sp == _sp, "must have correct argument count");
  2184   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2186   // First guess at the value type.
  2187   const Type *value_type = Type::get_const_basic_type(type);
  2189   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
  2190   // there was not enough information to nail it down.
  2191   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2192   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2194   // We will need memory barriers unless we can determine a unique
  2195   // alias category for this reference.  (Note:  If for some reason
  2196   // the barriers get omitted and the unsafe reference begins to "pollute"
  2197   // the alias analysis of the rest of the graph, either Compile::can_alias
  2198   // or Compile::must_alias will throw a diagnostic assert.)
  2199   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
  2201   if (!is_store && type == T_OBJECT) {
  2202     // Attempt to infer a sharper value type from the offset and base type.
  2203     ciKlass* sharpened_klass = NULL;
  2205     // See if it is an instance field, with an object type.
  2206     if (alias_type->field() != NULL) {
  2207       assert(!is_native_ptr, "native pointer op cannot use a java address");
  2208       if (alias_type->field()->type()->is_klass()) {
  2209         sharpened_klass = alias_type->field()->type()->as_klass();
  2213     // See if it is a narrow oop array.
  2214     if (adr_type->isa_aryptr()) {
  2215       if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
  2216         const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
  2217         if (elem_type != NULL) {
  2218           sharpened_klass = elem_type->klass();
  2223     if (sharpened_klass != NULL) {
  2224       const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
  2226       // Sharpen the value type.
  2227       value_type = tjp;
  2229 #ifndef PRODUCT
  2230       if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
  2231         tty->print("  from base type:  ");   adr_type->dump();
  2232         tty->print("  sharpened value: "); value_type->dump();
  2234 #endif
  2238   // Null check on self without removing any arguments.  The argument
  2239   // null check technically happens in the wrong place, which can lead to
  2240   // invalid stack traces when the primitive is inlined into a method
  2241   // which handles NullPointerExceptions.
  2242   _sp += nargs;
  2243   do_null_check(receiver, T_OBJECT);
  2244   _sp -= nargs;
  2245   if (stopped()) {
  2246     return true;
  2248   // Heap pointers get a null-check from the interpreter,
  2249   // as a courtesy.  However, this is not guaranteed by Unsafe,
  2250   // and it is not possible to fully distinguish unintended nulls
  2251   // from intended ones in this API.
  2253   if (is_volatile) {
  2254     // We need to emit leading and trailing CPU membars (see below) in
  2255     // addition to memory membars when is_volatile. This is a little
  2256     // too strong, but avoids the need to insert per-alias-type
  2257     // volatile membars (for stores; compare Parse::do_put_xxx), which
  2258     // we cannot do effectively here because we probably only have a
  2259     // rough approximation of type.
  2260     need_mem_bar = true;
  2261     // For Stores, place a memory ordering barrier now.
  2262     if (is_store)
  2263       insert_mem_bar(Op_MemBarRelease);
  2266   // Memory barrier to prevent normal and 'unsafe' accesses from
  2267   // bypassing each other.  Happens after null checks, so the
  2268   // exception paths do not take memory state from the memory barrier,
  2269   // so there's no problems making a strong assert about mixing users
  2270   // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
  2271   // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
  2272   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2274   if (!is_store) {
  2275     Node* p = make_load(control(), adr, value_type, type, adr_type, is_volatile);
  2276     // load value and push onto stack
  2277     switch (type) {
  2278     case T_BOOLEAN:
  2279     case T_CHAR:
  2280     case T_BYTE:
  2281     case T_SHORT:
  2282     case T_INT:
  2283     case T_FLOAT:
  2284     case T_OBJECT:
  2285       push( p );
  2286       break;
  2287     case T_ADDRESS:
  2288       // Cast to an int type.
  2289       p = _gvn.transform( new (C, 2) CastP2XNode(NULL,p) );
  2290       p = ConvX2L(p);
  2291       push_pair(p);
  2292       break;
  2293     case T_DOUBLE:
  2294     case T_LONG:
  2295       push_pair( p );
  2296       break;
  2297     default: ShouldNotReachHere();
  2299   } else {
  2300     // place effect of store into memory
  2301     switch (type) {
  2302     case T_DOUBLE:
  2303       val = dstore_rounding(val);
  2304       break;
  2305     case T_ADDRESS:
  2306       // Repackage the long as a pointer.
  2307       val = ConvL2X(val);
  2308       val = _gvn.transform( new (C, 2) CastX2PNode(val) );
  2309       break;
  2312     if (type != T_OBJECT ) {
  2313       (void) store_to_memory(control(), adr, val, type, adr_type, is_volatile);
  2314     } else {
  2315       // Possibly an oop being stored to Java heap or native memory
  2316       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
  2317         // oop to Java heap.
  2318         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
  2319       } else {
  2320         // We can't tell at compile time if we are storing in the Java heap or outside
  2321         // of it. So we need to emit code to conditionally do the proper type of
  2322         // store.
  2324         IdealKit ideal(gvn(), control(),  merged_memory());
  2325 #define __ ideal.
  2326         // QQQ who knows what probability is here??
  2327         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
  2328           // Sync IdealKit and graphKit.
  2329           set_all_memory( __ merged_memory());
  2330           set_control(__ ctrl());
  2331           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
  2332           // Update IdealKit memory.
  2333           __ set_all_memory(merged_memory());
  2334           __ set_ctrl(control());
  2335         } __ else_(); {
  2336           __ store(__ ctrl(), adr, val, type, alias_type->index(), is_volatile);
  2337         } __ end_if();
  2338         // Final sync IdealKit and GraphKit.
  2339         sync_kit(ideal);
  2340 #undef __
  2345   if (is_volatile) {
  2346     if (!is_store)
  2347       insert_mem_bar(Op_MemBarAcquire);
  2348     else
  2349       insert_mem_bar(Op_MemBarVolatile);
  2352   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
  2354   return true;
  2357 //----------------------------inline_unsafe_prefetch----------------------------
  2359 bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
  2360 #ifndef PRODUCT
  2362     ResourceMark rm;
  2363     // Check the signatures.
  2364     ciSignature* sig = signature();
  2365 #ifdef ASSERT
  2366     // Object getObject(Object base, int/long offset), etc.
  2367     BasicType rtype = sig->return_type()->basic_type();
  2368     if (!is_native_ptr) {
  2369       assert(sig->count() == 2, "oop prefetch has 2 arguments");
  2370       assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
  2371       assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
  2372     } else {
  2373       assert(sig->count() == 1, "native prefetch has 1 argument");
  2374       assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
  2376 #endif // ASSERT
  2378 #endif // !PRODUCT
  2380   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2382   // Argument words:  "this" if not static, plus (oop/offset) or (lo/hi) args
  2383   int nargs = (is_static ? 0 : 1) + (is_native_ptr ? 2 : 3);
  2385   debug_only(int saved_sp = _sp);
  2386   _sp += nargs;
  2388   // Build address expression.  See the code in inline_unsafe_access.
  2389   Node *adr;
  2390   if (!is_native_ptr) {
  2391     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
  2392     Node* offset = pop_pair();
  2393     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
  2394     Node* base   = pop();
  2395     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2396     // to be plain byte offsets, which are also the same as those accepted
  2397     // by oopDesc::field_base.
  2398     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  2399            "fieldOffset must be byte-scaled");
  2400     // 32-bit machines ignore the high half!
  2401     offset = ConvL2X(offset);
  2402     adr = make_unsafe_address(base, offset);
  2403   } else {
  2404     Node* ptr = pop_pair();
  2405     // Adjust Java long to machine word:
  2406     ptr = ConvL2X(ptr);
  2407     adr = make_unsafe_address(NULL, ptr);
  2410   if (is_static) {
  2411     assert(saved_sp == _sp, "must have correct argument count");
  2412   } else {
  2413     // Pop receiver last:  it was pushed first.
  2414     Node *receiver = pop();
  2415     assert(saved_sp == _sp, "must have correct argument count");
  2417     // Null check on self without removing any arguments.  The argument
  2418     // null check technically happens in the wrong place, which can lead to
  2419     // invalid stack traces when the primitive is inlined into a method
  2420     // which handles NullPointerExceptions.
  2421     _sp += nargs;
  2422     do_null_check(receiver, T_OBJECT);
  2423     _sp -= nargs;
  2424     if (stopped()) {
  2425       return true;
  2429   // Generate the read or write prefetch
  2430   Node *prefetch;
  2431   if (is_store) {
  2432     prefetch = new (C, 3) PrefetchWriteNode(i_o(), adr);
  2433   } else {
  2434     prefetch = new (C, 3) PrefetchReadNode(i_o(), adr);
  2436   prefetch->init_req(0, control());
  2437   set_i_o(_gvn.transform(prefetch));
  2439   return true;
  2442 //----------------------------inline_unsafe_CAS----------------------------
  2444 bool LibraryCallKit::inline_unsafe_CAS(BasicType type) {
  2445   // This basic scheme here is the same as inline_unsafe_access, but
  2446   // differs in enough details that combining them would make the code
  2447   // overly confusing.  (This is a true fact! I originally combined
  2448   // them, but even I was confused by it!) As much code/comments as
  2449   // possible are retained from inline_unsafe_access though to make
  2450   // the correspondences clearer. - dl
  2452   if (callee()->is_static())  return false;  // caller must have the capability!
  2454 #ifndef PRODUCT
  2456     ResourceMark rm;
  2457     // Check the signatures.
  2458     ciSignature* sig = signature();
  2459 #ifdef ASSERT
  2460     BasicType rtype = sig->return_type()->basic_type();
  2461     assert(rtype == T_BOOLEAN, "CAS must return boolean");
  2462     assert(sig->count() == 4, "CAS has 4 arguments");
  2463     assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
  2464     assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
  2465 #endif // ASSERT
  2467 #endif //PRODUCT
  2469   // number of stack slots per value argument (1 or 2)
  2470   int type_words = type2size[type];
  2472   // Cannot inline wide CAS on machines that don't support it natively
  2473   if (type2aelembytes(type) > BytesPerInt && !VM_Version::supports_cx8())
  2474     return false;
  2476   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2478   // Argument words:  "this" plus oop plus offset plus oldvalue plus newvalue;
  2479   int nargs = 1 + 1 + 2  + type_words + type_words;
  2481   // pop arguments: newval, oldval, offset, base, and receiver
  2482   debug_only(int saved_sp = _sp);
  2483   _sp += nargs;
  2484   Node* newval   = (type_words == 1) ? pop() : pop_pair();
  2485   Node* oldval   = (type_words == 1) ? pop() : pop_pair();
  2486   Node *offset   = pop_pair();
  2487   Node *base     = pop();
  2488   Node *receiver = pop();
  2489   assert(saved_sp == _sp, "must have correct argument count");
  2491   //  Null check receiver.
  2492   _sp += nargs;
  2493   do_null_check(receiver, T_OBJECT);
  2494   _sp -= nargs;
  2495   if (stopped()) {
  2496     return true;
  2499   // Build field offset expression.
  2500   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
  2501   // to be plain byte offsets, which are also the same as those accepted
  2502   // by oopDesc::field_base.
  2503   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  2504   // 32-bit machines ignore the high half of long offsets
  2505   offset = ConvL2X(offset);
  2506   Node* adr = make_unsafe_address(base, offset);
  2507   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2509   // (Unlike inline_unsafe_access, there seems no point in trying
  2510   // to refine types. Just use the coarse types here.
  2511   const Type *value_type = Type::get_const_basic_type(type);
  2512   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2513   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
  2514   int alias_idx = C->get_alias_index(adr_type);
  2516   // Memory-model-wise, a CAS acts like a little synchronized block,
  2517   // so needs barriers on each side.  These don't translate into
  2518   // actual barriers on most machines, but we still need rest of
  2519   // compiler to respect ordering.
  2521   insert_mem_bar(Op_MemBarRelease);
  2522   insert_mem_bar(Op_MemBarCPUOrder);
  2524   // 4984716: MemBars must be inserted before this
  2525   //          memory node in order to avoid a false
  2526   //          dependency which will confuse the scheduler.
  2527   Node *mem = memory(alias_idx);
  2529   // For now, we handle only those cases that actually exist: ints,
  2530   // longs, and Object. Adding others should be straightforward.
  2531   Node* cas;
  2532   switch(type) {
  2533   case T_INT:
  2534     cas = _gvn.transform(new (C, 5) CompareAndSwapINode(control(), mem, adr, newval, oldval));
  2535     break;
  2536   case T_LONG:
  2537     cas = _gvn.transform(new (C, 5) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
  2538     break;
  2539   case T_OBJECT:
  2540      // reference stores need a store barrier.
  2541     // (They don't if CAS fails, but it isn't worth checking.)
  2542     pre_barrier(control(), base, adr, alias_idx, newval, value_type->make_oopptr(), T_OBJECT);
  2543 #ifdef _LP64
  2544     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
  2545       Node *newval_enc = _gvn.transform(new (C, 2) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
  2546       Node *oldval_enc = _gvn.transform(new (C, 2) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
  2547       cas = _gvn.transform(new (C, 5) CompareAndSwapNNode(control(), mem, adr,
  2548                                                           newval_enc, oldval_enc));
  2549     } else
  2550 #endif
  2552       cas = _gvn.transform(new (C, 5) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
  2554     post_barrier(control(), cas, base, adr, alias_idx, newval, T_OBJECT, true);
  2555     break;
  2556   default:
  2557     ShouldNotReachHere();
  2558     break;
  2561   // SCMemProjNodes represent the memory state of CAS. Their main
  2562   // role is to prevent CAS nodes from being optimized away when their
  2563   // results aren't used.
  2564   Node* proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
  2565   set_memory(proj, alias_idx);
  2567   // Add the trailing membar surrounding the access
  2568   insert_mem_bar(Op_MemBarCPUOrder);
  2569   insert_mem_bar(Op_MemBarAcquire);
  2571   push(cas);
  2572   return true;
  2575 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
  2576   // This is another variant of inline_unsafe_access, differing in
  2577   // that it always issues store-store ("release") barrier and ensures
  2578   // store-atomicity (which only matters for "long").
  2580   if (callee()->is_static())  return false;  // caller must have the capability!
  2582 #ifndef PRODUCT
  2584     ResourceMark rm;
  2585     // Check the signatures.
  2586     ciSignature* sig = signature();
  2587 #ifdef ASSERT
  2588     BasicType rtype = sig->return_type()->basic_type();
  2589     assert(rtype == T_VOID, "must return void");
  2590     assert(sig->count() == 3, "has 3 arguments");
  2591     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
  2592     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
  2593 #endif // ASSERT
  2595 #endif //PRODUCT
  2597   // number of stack slots per value argument (1 or 2)
  2598   int type_words = type2size[type];
  2600   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  2602   // Argument words:  "this" plus oop plus offset plus value;
  2603   int nargs = 1 + 1 + 2 + type_words;
  2605   // pop arguments: val, offset, base, and receiver
  2606   debug_only(int saved_sp = _sp);
  2607   _sp += nargs;
  2608   Node* val      = (type_words == 1) ? pop() : pop_pair();
  2609   Node *offset   = pop_pair();
  2610   Node *base     = pop();
  2611   Node *receiver = pop();
  2612   assert(saved_sp == _sp, "must have correct argument count");
  2614   //  Null check receiver.
  2615   _sp += nargs;
  2616   do_null_check(receiver, T_OBJECT);
  2617   _sp -= nargs;
  2618   if (stopped()) {
  2619     return true;
  2622   // Build field offset expression.
  2623   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
  2624   // 32-bit machines ignore the high half of long offsets
  2625   offset = ConvL2X(offset);
  2626   Node* adr = make_unsafe_address(base, offset);
  2627   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
  2628   const Type *value_type = Type::get_const_basic_type(type);
  2629   Compile::AliasType* alias_type = C->alias_type(adr_type);
  2631   insert_mem_bar(Op_MemBarRelease);
  2632   insert_mem_bar(Op_MemBarCPUOrder);
  2633   // Ensure that the store is atomic for longs:
  2634   bool require_atomic_access = true;
  2635   Node* store;
  2636   if (type == T_OBJECT) // reference stores need a store barrier.
  2637     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type);
  2638   else {
  2639     store = store_to_memory(control(), adr, val, type, adr_type, require_atomic_access);
  2641   insert_mem_bar(Op_MemBarCPUOrder);
  2642   return true;
  2645 bool LibraryCallKit::inline_unsafe_allocate() {
  2646   if (callee()->is_static())  return false;  // caller must have the capability!
  2647   int nargs = 1 + 1;
  2648   assert(signature()->size() == nargs-1, "alloc has 1 argument");
  2649   null_check_receiver(callee());  // check then ignore argument(0)
  2650   _sp += nargs;  // set original stack for use by uncommon_trap
  2651   Node* cls = do_null_check(argument(1), T_OBJECT);
  2652   _sp -= nargs;
  2653   if (stopped())  return true;
  2655   Node* kls = load_klass_from_mirror(cls, false, nargs, NULL, 0);
  2656   _sp += nargs;  // set original stack for use by uncommon_trap
  2657   kls = do_null_check(kls, T_OBJECT);
  2658   _sp -= nargs;
  2659   if (stopped())  return true;  // argument was like int.class
  2661   // Note:  The argument might still be an illegal value like
  2662   // Serializable.class or Object[].class.   The runtime will handle it.
  2663   // But we must make an explicit check for initialization.
  2664   Node* insp = basic_plus_adr(kls, instanceKlass::init_state_offset_in_bytes() + sizeof(oopDesc));
  2665   Node* inst = make_load(NULL, insp, TypeInt::INT, T_INT);
  2666   Node* bits = intcon(instanceKlass::fully_initialized);
  2667   Node* test = _gvn.transform( new (C, 3) SubINode(inst, bits) );
  2668   // The 'test' is non-zero if we need to take a slow path.
  2670   Node* obj = new_instance(kls, test);
  2671   push(obj);
  2673   return true;
  2676 //------------------------inline_native_time_funcs--------------
  2677 // inline code for System.currentTimeMillis() and System.nanoTime()
  2678 // these have the same type and signature
  2679 bool LibraryCallKit::inline_native_time_funcs(bool isNano) {
  2680   address funcAddr = isNano ? CAST_FROM_FN_PTR(address, os::javaTimeNanos) :
  2681                               CAST_FROM_FN_PTR(address, os::javaTimeMillis);
  2682   const char * funcName = isNano ? "nanoTime" : "currentTimeMillis";
  2683   const TypeFunc *tf = OptoRuntime::current_time_millis_Type();
  2684   const TypePtr* no_memory_effects = NULL;
  2685   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
  2686   Node* value = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms+0));
  2687 #ifdef ASSERT
  2688   Node* value_top = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms + 1));
  2689   assert(value_top == top(), "second value must be top");
  2690 #endif
  2691   push_pair(value);
  2692   return true;
  2695 //------------------------inline_native_currentThread------------------
  2696 bool LibraryCallKit::inline_native_currentThread() {
  2697   Node* junk = NULL;
  2698   push(generate_current_thread(junk));
  2699   return true;
  2702 //------------------------inline_native_isInterrupted------------------
  2703 bool LibraryCallKit::inline_native_isInterrupted() {
  2704   const int nargs = 1+1;  // receiver + boolean
  2705   assert(nargs == arg_size(), "sanity");
  2706   // Add a fast path to t.isInterrupted(clear_int):
  2707   //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
  2708   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
  2709   // So, in the common case that the interrupt bit is false,
  2710   // we avoid making a call into the VM.  Even if the interrupt bit
  2711   // is true, if the clear_int argument is false, we avoid the VM call.
  2712   // However, if the receiver is not currentThread, we must call the VM,
  2713   // because there must be some locking done around the operation.
  2715   // We only go to the fast case code if we pass two guards.
  2716   // Paths which do not pass are accumulated in the slow_region.
  2717   RegionNode* slow_region = new (C, 1) RegionNode(1);
  2718   record_for_igvn(slow_region);
  2719   RegionNode* result_rgn = new (C, 4) RegionNode(1+3); // fast1, fast2, slow
  2720   PhiNode*    result_val = new (C, 4) PhiNode(result_rgn, TypeInt::BOOL);
  2721   enum { no_int_result_path   = 1,
  2722          no_clear_result_path = 2,
  2723          slow_result_path     = 3
  2724   };
  2726   // (a) Receiving thread must be the current thread.
  2727   Node* rec_thr = argument(0);
  2728   Node* tls_ptr = NULL;
  2729   Node* cur_thr = generate_current_thread(tls_ptr);
  2730   Node* cmp_thr = _gvn.transform( new (C, 3) CmpPNode(cur_thr, rec_thr) );
  2731   Node* bol_thr = _gvn.transform( new (C, 2) BoolNode(cmp_thr, BoolTest::ne) );
  2733   bool known_current_thread = (_gvn.type(bol_thr) == TypeInt::ZERO);
  2734   if (!known_current_thread)
  2735     generate_slow_guard(bol_thr, slow_region);
  2737   // (b) Interrupt bit on TLS must be false.
  2738   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
  2739   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
  2740   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
  2741   // Set the control input on the field _interrupted read to prevent it floating up.
  2742   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT);
  2743   Node* cmp_bit = _gvn.transform( new (C, 3) CmpINode(int_bit, intcon(0)) );
  2744   Node* bol_bit = _gvn.transform( new (C, 2) BoolNode(cmp_bit, BoolTest::ne) );
  2746   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
  2748   // First fast path:  if (!TLS._interrupted) return false;
  2749   Node* false_bit = _gvn.transform( new (C, 1) IfFalseNode(iff_bit) );
  2750   result_rgn->init_req(no_int_result_path, false_bit);
  2751   result_val->init_req(no_int_result_path, intcon(0));
  2753   // drop through to next case
  2754   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_bit)) );
  2756   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
  2757   Node* clr_arg = argument(1);
  2758   Node* cmp_arg = _gvn.transform( new (C, 3) CmpINode(clr_arg, intcon(0)) );
  2759   Node* bol_arg = _gvn.transform( new (C, 2) BoolNode(cmp_arg, BoolTest::ne) );
  2760   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
  2762   // Second fast path:  ... else if (!clear_int) return true;
  2763   Node* false_arg = _gvn.transform( new (C, 1) IfFalseNode(iff_arg) );
  2764   result_rgn->init_req(no_clear_result_path, false_arg);
  2765   result_val->init_req(no_clear_result_path, intcon(1));
  2767   // drop through to next case
  2768   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_arg)) );
  2770   // (d) Otherwise, go to the slow path.
  2771   slow_region->add_req(control());
  2772   set_control( _gvn.transform(slow_region) );
  2774   if (stopped()) {
  2775     // There is no slow path.
  2776     result_rgn->init_req(slow_result_path, top());
  2777     result_val->init_req(slow_result_path, top());
  2778   } else {
  2779     // non-virtual because it is a private non-static
  2780     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
  2782     Node* slow_val = set_results_for_java_call(slow_call);
  2783     // this->control() comes from set_results_for_java_call
  2785     // If we know that the result of the slow call will be true, tell the optimizer!
  2786     if (known_current_thread)  slow_val = intcon(1);
  2788     Node* fast_io  = slow_call->in(TypeFunc::I_O);
  2789     Node* fast_mem = slow_call->in(TypeFunc::Memory);
  2790     // These two phis are pre-filled with copies of of the fast IO and Memory
  2791     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
  2792     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
  2794     result_rgn->init_req(slow_result_path, control());
  2795     io_phi    ->init_req(slow_result_path, i_o());
  2796     mem_phi   ->init_req(slow_result_path, reset_memory());
  2797     result_val->init_req(slow_result_path, slow_val);
  2799     set_all_memory( _gvn.transform(mem_phi) );
  2800     set_i_o(        _gvn.transform(io_phi) );
  2803   push_result(result_rgn, result_val);
  2804   C->set_has_split_ifs(true); // Has chance for split-if optimization
  2806   return true;
  2809 //---------------------------load_mirror_from_klass----------------------------
  2810 // Given a klass oop, load its java mirror (a java.lang.Class oop).
  2811 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
  2812   Node* p = basic_plus_adr(klass, Klass::java_mirror_offset_in_bytes() + sizeof(oopDesc));
  2813   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT);
  2816 //-----------------------load_klass_from_mirror_common-------------------------
  2817 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
  2818 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
  2819 // and branch to the given path on the region.
  2820 // If never_see_null, take an uncommon trap on null, so we can optimistically
  2821 // compile for the non-null case.
  2822 // If the region is NULL, force never_see_null = true.
  2823 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
  2824                                                     bool never_see_null,
  2825                                                     int nargs,
  2826                                                     RegionNode* region,
  2827                                                     int null_path,
  2828                                                     int offset) {
  2829   if (region == NULL)  never_see_null = true;
  2830   Node* p = basic_plus_adr(mirror, offset);
  2831   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  2832   Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type) );
  2833   _sp += nargs; // any deopt will start just before call to enclosing method
  2834   Node* null_ctl = top();
  2835   kls = null_check_oop(kls, &null_ctl, never_see_null);
  2836   if (region != NULL) {
  2837     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
  2838     region->init_req(null_path, null_ctl);
  2839   } else {
  2840     assert(null_ctl == top(), "no loose ends");
  2842   _sp -= nargs;
  2843   return kls;
  2846 //--------------------(inline_native_Class_query helpers)---------------------
  2847 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
  2848 // Fall through if (mods & mask) == bits, take the guard otherwise.
  2849 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
  2850   // Branch around if the given klass has the given modifier bit set.
  2851   // Like generate_guard, adds a new path onto the region.
  2852   Node* modp = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
  2853   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT);
  2854   Node* mask = intcon(modifier_mask);
  2855   Node* bits = intcon(modifier_bits);
  2856   Node* mbit = _gvn.transform( new (C, 3) AndINode(mods, mask) );
  2857   Node* cmp  = _gvn.transform( new (C, 3) CmpINode(mbit, bits) );
  2858   Node* bol  = _gvn.transform( new (C, 2) BoolNode(cmp, BoolTest::ne) );
  2859   return generate_fair_guard(bol, region);
  2861 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
  2862   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
  2865 //-------------------------inline_native_Class_query-------------------
  2866 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
  2867   int nargs = 1+0;  // just the Class mirror, in most cases
  2868   const Type* return_type = TypeInt::BOOL;
  2869   Node* prim_return_value = top();  // what happens if it's a primitive class?
  2870   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  2871   bool expect_prim = false;     // most of these guys expect to work on refs
  2873   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
  2875   switch (id) {
  2876   case vmIntrinsics::_isInstance:
  2877     nargs = 1+1;  // the Class mirror, plus the object getting queried about
  2878     // nothing is an instance of a primitive type
  2879     prim_return_value = intcon(0);
  2880     break;
  2881   case vmIntrinsics::_getModifiers:
  2882     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  2883     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
  2884     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
  2885     break;
  2886   case vmIntrinsics::_isInterface:
  2887     prim_return_value = intcon(0);
  2888     break;
  2889   case vmIntrinsics::_isArray:
  2890     prim_return_value = intcon(0);
  2891     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
  2892     break;
  2893   case vmIntrinsics::_isPrimitive:
  2894     prim_return_value = intcon(1);
  2895     expect_prim = true;  // obviously
  2896     break;
  2897   case vmIntrinsics::_getSuperclass:
  2898     prim_return_value = null();
  2899     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  2900     break;
  2901   case vmIntrinsics::_getComponentType:
  2902     prim_return_value = null();
  2903     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
  2904     break;
  2905   case vmIntrinsics::_getClassAccessFlags:
  2906     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
  2907     return_type = TypeInt::INT;  // not bool!  6297094
  2908     break;
  2909   default:
  2910     ShouldNotReachHere();
  2913   Node* mirror =                      argument(0);
  2914   Node* obj    = (nargs <= 1)? top(): argument(1);
  2916   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
  2917   if (mirror_con == NULL)  return false;  // cannot happen?
  2919 #ifndef PRODUCT
  2920   if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
  2921     ciType* k = mirror_con->java_mirror_type();
  2922     if (k) {
  2923       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
  2924       k->print_name();
  2925       tty->cr();
  2928 #endif
  2930   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
  2931   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  2932   record_for_igvn(region);
  2933   PhiNode* phi = new (C, PATH_LIMIT) PhiNode(region, return_type);
  2935   // The mirror will never be null of Reflection.getClassAccessFlags, however
  2936   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
  2937   // if it is. See bug 4774291.
  2939   // For Reflection.getClassAccessFlags(), the null check occurs in
  2940   // the wrong place; see inline_unsafe_access(), above, for a similar
  2941   // situation.
  2942   _sp += nargs;  // set original stack for use by uncommon_trap
  2943   mirror = do_null_check(mirror, T_OBJECT);
  2944   _sp -= nargs;
  2945   // If mirror or obj is dead, only null-path is taken.
  2946   if (stopped())  return true;
  2948   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
  2950   // Now load the mirror's klass metaobject, and null-check it.
  2951   // Side-effects region with the control path if the klass is null.
  2952   Node* kls = load_klass_from_mirror(mirror, never_see_null, nargs,
  2953                                      region, _prim_path);
  2954   // If kls is null, we have a primitive mirror.
  2955   phi->init_req(_prim_path, prim_return_value);
  2956   if (stopped()) { push_result(region, phi); return true; }
  2958   Node* p;  // handy temp
  2959   Node* null_ctl;
  2961   // Now that we have the non-null klass, we can perform the real query.
  2962   // For constant classes, the query will constant-fold in LoadNode::Value.
  2963   Node* query_value = top();
  2964   switch (id) {
  2965   case vmIntrinsics::_isInstance:
  2966     // nothing is an instance of a primitive type
  2967     _sp += nargs;          // gen_instanceof might do an uncommon trap
  2968     query_value = gen_instanceof(obj, kls);
  2969     _sp -= nargs;
  2970     break;
  2972   case vmIntrinsics::_getModifiers:
  2973     p = basic_plus_adr(kls, Klass::modifier_flags_offset_in_bytes() + sizeof(oopDesc));
  2974     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
  2975     break;
  2977   case vmIntrinsics::_isInterface:
  2978     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  2979     if (generate_interface_guard(kls, region) != NULL)
  2980       // A guard was added.  If the guard is taken, it was an interface.
  2981       phi->add_req(intcon(1));
  2982     // If we fall through, it's a plain class.
  2983     query_value = intcon(0);
  2984     break;
  2986   case vmIntrinsics::_isArray:
  2987     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
  2988     if (generate_array_guard(kls, region) != NULL)
  2989       // A guard was added.  If the guard is taken, it was an array.
  2990       phi->add_req(intcon(1));
  2991     // If we fall through, it's a plain class.
  2992     query_value = intcon(0);
  2993     break;
  2995   case vmIntrinsics::_isPrimitive:
  2996     query_value = intcon(0); // "normal" path produces false
  2997     break;
  2999   case vmIntrinsics::_getSuperclass:
  3000     // The rules here are somewhat unfortunate, but we can still do better
  3001     // with random logic than with a JNI call.
  3002     // Interfaces store null or Object as _super, but must report null.
  3003     // Arrays store an intermediate super as _super, but must report Object.
  3004     // Other types can report the actual _super.
  3005     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
  3006     if (generate_interface_guard(kls, region) != NULL)
  3007       // A guard was added.  If the guard is taken, it was an interface.
  3008       phi->add_req(null());
  3009     if (generate_array_guard(kls, region) != NULL)
  3010       // A guard was added.  If the guard is taken, it was an array.
  3011       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
  3012     // If we fall through, it's a plain class.  Get its _super.
  3013     p = basic_plus_adr(kls, Klass::super_offset_in_bytes() + sizeof(oopDesc));
  3014     kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL) );
  3015     null_ctl = top();
  3016     kls = null_check_oop(kls, &null_ctl);
  3017     if (null_ctl != top()) {
  3018       // If the guard is taken, Object.superClass is null (both klass and mirror).
  3019       region->add_req(null_ctl);
  3020       phi   ->add_req(null());
  3022     if (!stopped()) {
  3023       query_value = load_mirror_from_klass(kls);
  3025     break;
  3027   case vmIntrinsics::_getComponentType:
  3028     if (generate_array_guard(kls, region) != NULL) {
  3029       // Be sure to pin the oop load to the guard edge just created:
  3030       Node* is_array_ctrl = region->in(region->req()-1);
  3031       Node* cma = basic_plus_adr(kls, in_bytes(arrayKlass::component_mirror_offset()) + sizeof(oopDesc));
  3032       Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT);
  3033       phi->add_req(cmo);
  3035     query_value = null();  // non-array case is null
  3036     break;
  3038   case vmIntrinsics::_getClassAccessFlags:
  3039     p = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
  3040     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
  3041     break;
  3043   default:
  3044     ShouldNotReachHere();
  3047   // Fall-through is the normal case of a query to a real class.
  3048   phi->init_req(1, query_value);
  3049   region->init_req(1, control());
  3051   push_result(region, phi);
  3052   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3054   return true;
  3057 //--------------------------inline_native_subtype_check------------------------
  3058 // This intrinsic takes the JNI calls out of the heart of
  3059 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
  3060 bool LibraryCallKit::inline_native_subtype_check() {
  3061   int nargs = 1+1;  // the Class mirror, plus the other class getting examined
  3063   // Pull both arguments off the stack.
  3064   Node* args[2];                // two java.lang.Class mirrors: superc, subc
  3065   args[0] = argument(0);
  3066   args[1] = argument(1);
  3067   Node* klasses[2];             // corresponding Klasses: superk, subk
  3068   klasses[0] = klasses[1] = top();
  3070   enum {
  3071     // A full decision tree on {superc is prim, subc is prim}:
  3072     _prim_0_path = 1,           // {P,N} => false
  3073                                 // {P,P} & superc!=subc => false
  3074     _prim_same_path,            // {P,P} & superc==subc => true
  3075     _prim_1_path,               // {N,P} => false
  3076     _ref_subtype_path,          // {N,N} & subtype check wins => true
  3077     _both_ref_path,             // {N,N} & subtype check loses => false
  3078     PATH_LIMIT
  3079   };
  3081   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  3082   Node*       phi    = new (C, PATH_LIMIT) PhiNode(region, TypeInt::BOOL);
  3083   record_for_igvn(region);
  3085   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
  3086   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
  3087   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
  3089   // First null-check both mirrors and load each mirror's klass metaobject.
  3090   int which_arg;
  3091   for (which_arg = 0; which_arg <= 1; which_arg++) {
  3092     Node* arg = args[which_arg];
  3093     _sp += nargs;  // set original stack for use by uncommon_trap
  3094     arg = do_null_check(arg, T_OBJECT);
  3095     _sp -= nargs;
  3096     if (stopped())  break;
  3097     args[which_arg] = _gvn.transform(arg);
  3099     Node* p = basic_plus_adr(arg, class_klass_offset);
  3100     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
  3101     klasses[which_arg] = _gvn.transform(kls);
  3104   // Having loaded both klasses, test each for null.
  3105   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3106   for (which_arg = 0; which_arg <= 1; which_arg++) {
  3107     Node* kls = klasses[which_arg];
  3108     Node* null_ctl = top();
  3109     _sp += nargs;  // set original stack for use by uncommon_trap
  3110     kls = null_check_oop(kls, &null_ctl, never_see_null);
  3111     _sp -= nargs;
  3112     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
  3113     region->init_req(prim_path, null_ctl);
  3114     if (stopped())  break;
  3115     klasses[which_arg] = kls;
  3118   if (!stopped()) {
  3119     // now we have two reference types, in klasses[0..1]
  3120     Node* subk   = klasses[1];  // the argument to isAssignableFrom
  3121     Node* superk = klasses[0];  // the receiver
  3122     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
  3123     // now we have a successful reference subtype check
  3124     region->set_req(_ref_subtype_path, control());
  3127   // If both operands are primitive (both klasses null), then
  3128   // we must return true when they are identical primitives.
  3129   // It is convenient to test this after the first null klass check.
  3130   set_control(region->in(_prim_0_path)); // go back to first null check
  3131   if (!stopped()) {
  3132     // Since superc is primitive, make a guard for the superc==subc case.
  3133     Node* cmp_eq = _gvn.transform( new (C, 3) CmpPNode(args[0], args[1]) );
  3134     Node* bol_eq = _gvn.transform( new (C, 2) BoolNode(cmp_eq, BoolTest::eq) );
  3135     generate_guard(bol_eq, region, PROB_FAIR);
  3136     if (region->req() == PATH_LIMIT+1) {
  3137       // A guard was added.  If the added guard is taken, superc==subc.
  3138       region->swap_edges(PATH_LIMIT, _prim_same_path);
  3139       region->del_req(PATH_LIMIT);
  3141     region->set_req(_prim_0_path, control()); // Not equal after all.
  3144   // these are the only paths that produce 'true':
  3145   phi->set_req(_prim_same_path,   intcon(1));
  3146   phi->set_req(_ref_subtype_path, intcon(1));
  3148   // pull together the cases:
  3149   assert(region->req() == PATH_LIMIT, "sane region");
  3150   for (uint i = 1; i < region->req(); i++) {
  3151     Node* ctl = region->in(i);
  3152     if (ctl == NULL || ctl == top()) {
  3153       region->set_req(i, top());
  3154       phi   ->set_req(i, top());
  3155     } else if (phi->in(i) == NULL) {
  3156       phi->set_req(i, intcon(0)); // all other paths produce 'false'
  3160   set_control(_gvn.transform(region));
  3161   push(_gvn.transform(phi));
  3163   return true;
  3166 //---------------------generate_array_guard_common------------------------
  3167 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
  3168                                                   bool obj_array, bool not_array) {
  3169   // If obj_array/non_array==false/false:
  3170   // Branch around if the given klass is in fact an array (either obj or prim).
  3171   // If obj_array/non_array==false/true:
  3172   // Branch around if the given klass is not an array klass of any kind.
  3173   // If obj_array/non_array==true/true:
  3174   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
  3175   // If obj_array/non_array==true/false:
  3176   // Branch around if the kls is an oop array (Object[] or subtype)
  3177   //
  3178   // Like generate_guard, adds a new path onto the region.
  3179   jint  layout_con = 0;
  3180   Node* layout_val = get_layout_helper(kls, layout_con);
  3181   if (layout_val == NULL) {
  3182     bool query = (obj_array
  3183                   ? Klass::layout_helper_is_objArray(layout_con)
  3184                   : Klass::layout_helper_is_javaArray(layout_con));
  3185     if (query == not_array) {
  3186       return NULL;                       // never a branch
  3187     } else {                             // always a branch
  3188       Node* always_branch = control();
  3189       if (region != NULL)
  3190         region->add_req(always_branch);
  3191       set_control(top());
  3192       return always_branch;
  3195   // Now test the correct condition.
  3196   jint  nval = (obj_array
  3197                 ? ((jint)Klass::_lh_array_tag_type_value
  3198                    <<    Klass::_lh_array_tag_shift)
  3199                 : Klass::_lh_neutral_value);
  3200   Node* cmp = _gvn.transform( new(C, 3) CmpINode(layout_val, intcon(nval)) );
  3201   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
  3202   // invert the test if we are looking for a non-array
  3203   if (not_array)  btest = BoolTest(btest).negate();
  3204   Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, btest) );
  3205   return generate_fair_guard(bol, region);
  3209 //-----------------------inline_native_newArray--------------------------
  3210 bool LibraryCallKit::inline_native_newArray() {
  3211   int nargs = 2;
  3212   Node* mirror    = argument(0);
  3213   Node* count_val = argument(1);
  3215   _sp += nargs;  // set original stack for use by uncommon_trap
  3216   mirror = do_null_check(mirror, T_OBJECT);
  3217   _sp -= nargs;
  3218   // If mirror or obj is dead, only null-path is taken.
  3219   if (stopped())  return true;
  3221   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
  3222   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  3223   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
  3224                                                       TypeInstPtr::NOTNULL);
  3225   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  3226   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  3227                                                       TypePtr::BOTTOM);
  3229   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
  3230   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
  3231                                                   nargs,
  3232                                                   result_reg, _slow_path);
  3233   Node* normal_ctl   = control();
  3234   Node* no_array_ctl = result_reg->in(_slow_path);
  3236   // Generate code for the slow case.  We make a call to newArray().
  3237   set_control(no_array_ctl);
  3238   if (!stopped()) {
  3239     // Either the input type is void.class, or else the
  3240     // array klass has not yet been cached.  Either the
  3241     // ensuing call will throw an exception, or else it
  3242     // will cache the array klass for next time.
  3243     PreserveJVMState pjvms(this);
  3244     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
  3245     Node* slow_result = set_results_for_java_call(slow_call);
  3246     // this->control() comes from set_results_for_java_call
  3247     result_reg->set_req(_slow_path, control());
  3248     result_val->set_req(_slow_path, slow_result);
  3249     result_io ->set_req(_slow_path, i_o());
  3250     result_mem->set_req(_slow_path, reset_memory());
  3253   set_control(normal_ctl);
  3254   if (!stopped()) {
  3255     // Normal case:  The array type has been cached in the java.lang.Class.
  3256     // The following call works fine even if the array type is polymorphic.
  3257     // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3258     Node* obj = new_array(klass_node, count_val, nargs);
  3259     result_reg->init_req(_normal_path, control());
  3260     result_val->init_req(_normal_path, obj);
  3261     result_io ->init_req(_normal_path, i_o());
  3262     result_mem->init_req(_normal_path, reset_memory());
  3265   // Return the combined state.
  3266   set_i_o(        _gvn.transform(result_io)  );
  3267   set_all_memory( _gvn.transform(result_mem) );
  3268   push_result(result_reg, result_val);
  3269   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3271   return true;
  3274 //----------------------inline_native_getLength--------------------------
  3275 bool LibraryCallKit::inline_native_getLength() {
  3276   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3278   int nargs = 1;
  3279   Node* array = argument(0);
  3281   _sp += nargs;  // set original stack for use by uncommon_trap
  3282   array = do_null_check(array, T_OBJECT);
  3283   _sp -= nargs;
  3285   // If array is dead, only null-path is taken.
  3286   if (stopped())  return true;
  3288   // Deoptimize if it is a non-array.
  3289   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
  3291   if (non_array != NULL) {
  3292     PreserveJVMState pjvms(this);
  3293     set_control(non_array);
  3294     _sp += nargs;  // push the arguments back on the stack
  3295     uncommon_trap(Deoptimization::Reason_intrinsic,
  3296                   Deoptimization::Action_maybe_recompile);
  3299   // If control is dead, only non-array-path is taken.
  3300   if (stopped())  return true;
  3302   // The works fine even if the array type is polymorphic.
  3303   // It could be a dynamic mix of int[], boolean[], Object[], etc.
  3304   push( load_array_length(array) );
  3306   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3308   return true;
  3311 //------------------------inline_array_copyOf----------------------------
  3312 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
  3313   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
  3315   // Restore the stack and pop off the arguments.
  3316   int nargs = 3 + (is_copyOfRange? 1: 0);
  3317   Node* original          = argument(0);
  3318   Node* start             = is_copyOfRange? argument(1): intcon(0);
  3319   Node* end               = is_copyOfRange? argument(2): argument(1);
  3320   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
  3322   Node* newcopy;
  3324   //set the original stack and the reexecute bit for the interpreter to reexecute
  3325   //the bytecode that invokes Arrays.copyOf if deoptimization happens
  3326   { PreserveReexecuteState preexecs(this);
  3327     _sp += nargs;
  3328     jvms()->set_should_reexecute(true);
  3330     array_type_mirror = do_null_check(array_type_mirror, T_OBJECT);
  3331     original          = do_null_check(original, T_OBJECT);
  3333     // Check if a null path was taken unconditionally.
  3334     if (stopped())  return true;
  3336     Node* orig_length = load_array_length(original);
  3338     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, 0,
  3339                                               NULL, 0);
  3340     klass_node = do_null_check(klass_node, T_OBJECT);
  3342     RegionNode* bailout = new (C, 1) RegionNode(1);
  3343     record_for_igvn(bailout);
  3345     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
  3346     // Bail out if that is so.
  3347     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
  3348     if (not_objArray != NULL) {
  3349       // Improve the klass node's type from the new optimistic assumption:
  3350       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
  3351       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
  3352       Node* cast = new (C, 2) CastPPNode(klass_node, akls);
  3353       cast->init_req(0, control());
  3354       klass_node = _gvn.transform(cast);
  3357     // Bail out if either start or end is negative.
  3358     generate_negative_guard(start, bailout, &start);
  3359     generate_negative_guard(end,   bailout, &end);
  3361     Node* length = end;
  3362     if (_gvn.type(start) != TypeInt::ZERO) {
  3363       length = _gvn.transform( new (C, 3) SubINode(end, start) );
  3366     // Bail out if length is negative.
  3367     // ...Not needed, since the new_array will throw the right exception.
  3368     //generate_negative_guard(length, bailout, &length);
  3370     if (bailout->req() > 1) {
  3371       PreserveJVMState pjvms(this);
  3372       set_control( _gvn.transform(bailout) );
  3373       uncommon_trap(Deoptimization::Reason_intrinsic,
  3374                     Deoptimization::Action_maybe_recompile);
  3377     if (!stopped()) {
  3379       // How many elements will we copy from the original?
  3380       // The answer is MinI(orig_length - start, length).
  3381       Node* orig_tail = _gvn.transform( new(C, 3) SubINode(orig_length, start) );
  3382       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
  3384       const bool raw_mem_only = true;
  3385       newcopy = new_array(klass_node, length, 0, raw_mem_only);
  3387       // Generate a direct call to the right arraycopy function(s).
  3388       // We know the copy is disjoint but we might not know if the
  3389       // oop stores need checking.
  3390       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
  3391       // This will fail a store-check if x contains any non-nulls.
  3392       bool disjoint_bases = true;
  3393       bool length_never_negative = true;
  3394       generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  3395                          original, start, newcopy, intcon(0), moved,
  3396                          disjoint_bases, length_never_negative);
  3398   } //original reexecute and sp are set back here
  3400   if(!stopped()) {
  3401     push(newcopy);
  3404   C->set_has_split_ifs(true); // Has chance for split-if optimization
  3406   return true;
  3410 //----------------------generate_virtual_guard---------------------------
  3411 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
  3412 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
  3413                                              RegionNode* slow_region) {
  3414   ciMethod* method = callee();
  3415   int vtable_index = method->vtable_index();
  3416   // Get the methodOop out of the appropriate vtable entry.
  3417   int entry_offset  = (instanceKlass::vtable_start_offset() +
  3418                      vtable_index*vtableEntry::size()) * wordSize +
  3419                      vtableEntry::method_offset_in_bytes();
  3420   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
  3421   Node* target_call = make_load(NULL, entry_addr, TypeInstPtr::NOTNULL, T_OBJECT);
  3423   // Compare the target method with the expected method (e.g., Object.hashCode).
  3424   const TypeInstPtr* native_call_addr = TypeInstPtr::make(method);
  3426   Node* native_call = makecon(native_call_addr);
  3427   Node* chk_native  = _gvn.transform( new(C, 3) CmpPNode(target_call, native_call) );
  3428   Node* test_native = _gvn.transform( new(C, 2) BoolNode(chk_native, BoolTest::ne) );
  3430   return generate_slow_guard(test_native, slow_region);
  3433 //-----------------------generate_method_call----------------------------
  3434 // Use generate_method_call to make a slow-call to the real
  3435 // method if the fast path fails.  An alternative would be to
  3436 // use a stub like OptoRuntime::slow_arraycopy_Java.
  3437 // This only works for expanding the current library call,
  3438 // not another intrinsic.  (E.g., don't use this for making an
  3439 // arraycopy call inside of the copyOf intrinsic.)
  3440 CallJavaNode*
  3441 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
  3442   // When compiling the intrinsic method itself, do not use this technique.
  3443   guarantee(callee() != C->method(), "cannot make slow-call to self");
  3445   ciMethod* method = callee();
  3446   // ensure the JVMS we have will be correct for this call
  3447   guarantee(method_id == method->intrinsic_id(), "must match");
  3449   const TypeFunc* tf = TypeFunc::make(method);
  3450   int tfdc = tf->domain()->cnt();
  3451   CallJavaNode* slow_call;
  3452   if (is_static) {
  3453     assert(!is_virtual, "");
  3454     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
  3455                                 SharedRuntime::get_resolve_static_call_stub(),
  3456                                 method, bci());
  3457   } else if (is_virtual) {
  3458     null_check_receiver(method);
  3459     int vtable_index = methodOopDesc::invalid_vtable_index;
  3460     if (UseInlineCaches) {
  3461       // Suppress the vtable call
  3462     } else {
  3463       // hashCode and clone are not a miranda methods,
  3464       // so the vtable index is fixed.
  3465       // No need to use the linkResolver to get it.
  3466        vtable_index = method->vtable_index();
  3468     slow_call = new(C, tfdc) CallDynamicJavaNode(tf,
  3469                                 SharedRuntime::get_resolve_virtual_call_stub(),
  3470                                 method, vtable_index, bci());
  3471   } else {  // neither virtual nor static:  opt_virtual
  3472     null_check_receiver(method);
  3473     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
  3474                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
  3475                                 method, bci());
  3476     slow_call->set_optimized_virtual(true);
  3478   set_arguments_for_java_call(slow_call);
  3479   set_edges_for_java_call(slow_call);
  3480   return slow_call;
  3484 //------------------------------inline_native_hashcode--------------------
  3485 // Build special case code for calls to hashCode on an object.
  3486 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
  3487   assert(is_static == callee()->is_static(), "correct intrinsic selection");
  3488   assert(!(is_virtual && is_static), "either virtual, special, or static");
  3490   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
  3492   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  3493   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
  3494                                                       TypeInt::INT);
  3495   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  3496   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  3497                                                       TypePtr::BOTTOM);
  3498   Node* obj = NULL;
  3499   if (!is_static) {
  3500     // Check for hashing null object
  3501     obj = null_check_receiver(callee());
  3502     if (stopped())  return true;        // unconditionally null
  3503     result_reg->init_req(_null_path, top());
  3504     result_val->init_req(_null_path, top());
  3505   } else {
  3506     // Do a null check, and return zero if null.
  3507     // System.identityHashCode(null) == 0
  3508     obj = argument(0);
  3509     Node* null_ctl = top();
  3510     obj = null_check_oop(obj, &null_ctl);
  3511     result_reg->init_req(_null_path, null_ctl);
  3512     result_val->init_req(_null_path, _gvn.intcon(0));
  3515   // Unconditionally null?  Then return right away.
  3516   if (stopped()) {
  3517     set_control( result_reg->in(_null_path) );
  3518     if (!stopped())
  3519       push(      result_val ->in(_null_path) );
  3520     return true;
  3523   // After null check, get the object's klass.
  3524   Node* obj_klass = load_object_klass(obj);
  3526   // This call may be virtual (invokevirtual) or bound (invokespecial).
  3527   // For each case we generate slightly different code.
  3529   // We only go to the fast case code if we pass a number of guards.  The
  3530   // paths which do not pass are accumulated in the slow_region.
  3531   RegionNode* slow_region = new (C, 1) RegionNode(1);
  3532   record_for_igvn(slow_region);
  3534   // If this is a virtual call, we generate a funny guard.  We pull out
  3535   // the vtable entry corresponding to hashCode() from the target object.
  3536   // If the target method which we are calling happens to be the native
  3537   // Object hashCode() method, we pass the guard.  We do not need this
  3538   // guard for non-virtual calls -- the caller is known to be the native
  3539   // Object hashCode().
  3540   if (is_virtual) {
  3541     generate_virtual_guard(obj_klass, slow_region);
  3544   // Get the header out of the object, use LoadMarkNode when available
  3545   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
  3546   Node* header = make_load(control(), header_addr, TypeX_X, TypeX_X->basic_type());
  3548   // Test the header to see if it is unlocked.
  3549   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
  3550   Node *lmasked_header = _gvn.transform( new (C, 3) AndXNode(header, lock_mask) );
  3551   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
  3552   Node *chk_unlocked   = _gvn.transform( new (C, 3) CmpXNode( lmasked_header, unlocked_val));
  3553   Node *test_unlocked  = _gvn.transform( new (C, 2) BoolNode( chk_unlocked, BoolTest::ne) );
  3555   generate_slow_guard(test_unlocked, slow_region);
  3557   // Get the hash value and check to see that it has been properly assigned.
  3558   // We depend on hash_mask being at most 32 bits and avoid the use of
  3559   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
  3560   // vm: see markOop.hpp.
  3561   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
  3562   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
  3563   Node *hshifted_header= _gvn.transform( new (C, 3) URShiftXNode(header, hash_shift) );
  3564   // This hack lets the hash bits live anywhere in the mark object now, as long
  3565   // as the shift drops the relevant bits into the low 32 bits.  Note that
  3566   // Java spec says that HashCode is an int so there's no point in capturing
  3567   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
  3568   hshifted_header      = ConvX2I(hshifted_header);
  3569   Node *hash_val       = _gvn.transform( new (C, 3) AndINode(hshifted_header, hash_mask) );
  3571   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
  3572   Node *chk_assigned   = _gvn.transform( new (C, 3) CmpINode( hash_val, no_hash_val));
  3573   Node *test_assigned  = _gvn.transform( new (C, 2) BoolNode( chk_assigned, BoolTest::eq) );
  3575   generate_slow_guard(test_assigned, slow_region);
  3577   Node* init_mem = reset_memory();
  3578   // fill in the rest of the null path:
  3579   result_io ->init_req(_null_path, i_o());
  3580   result_mem->init_req(_null_path, init_mem);
  3582   result_val->init_req(_fast_path, hash_val);
  3583   result_reg->init_req(_fast_path, control());
  3584   result_io ->init_req(_fast_path, i_o());
  3585   result_mem->init_req(_fast_path, init_mem);
  3587   // Generate code for the slow case.  We make a call to hashCode().
  3588   set_control(_gvn.transform(slow_region));
  3589   if (!stopped()) {
  3590     // No need for PreserveJVMState, because we're using up the present state.
  3591     set_all_memory(init_mem);
  3592     vmIntrinsics::ID hashCode_id = vmIntrinsics::_hashCode;
  3593     if (is_static)   hashCode_id = vmIntrinsics::_identityHashCode;
  3594     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
  3595     Node* slow_result = set_results_for_java_call(slow_call);
  3596     // this->control() comes from set_results_for_java_call
  3597     result_reg->init_req(_slow_path, control());
  3598     result_val->init_req(_slow_path, slow_result);
  3599     result_io  ->set_req(_slow_path, i_o());
  3600     result_mem ->set_req(_slow_path, reset_memory());
  3603   // Return the combined state.
  3604   set_i_o(        _gvn.transform(result_io)  );
  3605   set_all_memory( _gvn.transform(result_mem) );
  3606   push_result(result_reg, result_val);
  3608   return true;
  3611 //---------------------------inline_native_getClass----------------------------
  3612 // Build special case code for calls to getClass on an object.
  3613 bool LibraryCallKit::inline_native_getClass() {
  3614   Node* obj = null_check_receiver(callee());
  3615   if (stopped())  return true;
  3616   push( load_mirror_from_klass(load_object_klass(obj)) );
  3617   return true;
  3620 //-----------------inline_native_Reflection_getCallerClass---------------------
  3621 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
  3622 //
  3623 // NOTE that this code must perform the same logic as
  3624 // vframeStream::security_get_caller_frame in that it must skip
  3625 // Method.invoke() and auxiliary frames.
  3630 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
  3631   ciMethod*       method = callee();
  3633 #ifndef PRODUCT
  3634   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3635     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
  3637 #endif
  3639   debug_only(int saved_sp = _sp);
  3641   // Argument words:  (int depth)
  3642   int nargs = 1;
  3644   _sp += nargs;
  3645   Node* caller_depth_node = pop();
  3647   assert(saved_sp == _sp, "must have correct argument count");
  3649   // The depth value must be a constant in order for the runtime call
  3650   // to be eliminated.
  3651   const TypeInt* caller_depth_type = _gvn.type(caller_depth_node)->isa_int();
  3652   if (caller_depth_type == NULL || !caller_depth_type->is_con()) {
  3653 #ifndef PRODUCT
  3654     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3655       tty->print_cr("  Bailing out because caller depth was not a constant");
  3657 #endif
  3658     return false;
  3660   // Note that the JVM state at this point does not include the
  3661   // getCallerClass() frame which we are trying to inline. The
  3662   // semantics of getCallerClass(), however, are that the "first"
  3663   // frame is the getCallerClass() frame, so we subtract one from the
  3664   // requested depth before continuing. We don't inline requests of
  3665   // getCallerClass(0).
  3666   int caller_depth = caller_depth_type->get_con() - 1;
  3667   if (caller_depth < 0) {
  3668 #ifndef PRODUCT
  3669     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3670       tty->print_cr("  Bailing out because caller depth was %d", caller_depth);
  3672 #endif
  3673     return false;
  3676   if (!jvms()->has_method()) {
  3677 #ifndef PRODUCT
  3678     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3679       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
  3681 #endif
  3682     return false;
  3684   int _depth = jvms()->depth();  // cache call chain depth
  3686   // Walk back up the JVM state to find the caller at the required
  3687   // depth. NOTE that this code must perform the same logic as
  3688   // vframeStream::security_get_caller_frame in that it must skip
  3689   // Method.invoke() and auxiliary frames. Note also that depth is
  3690   // 1-based (1 is the bottom of the inlining).
  3691   int inlining_depth = _depth;
  3692   JVMState* caller_jvms = NULL;
  3694   if (inlining_depth > 0) {
  3695     caller_jvms = jvms();
  3696     assert(caller_jvms = jvms()->of_depth(inlining_depth), "inlining_depth == our depth");
  3697     do {
  3698       // The following if-tests should be performed in this order
  3699       if (is_method_invoke_or_aux_frame(caller_jvms)) {
  3700         // Skip a Method.invoke() or auxiliary frame
  3701       } else if (caller_depth > 0) {
  3702         // Skip real frame
  3703         --caller_depth;
  3704       } else {
  3705         // We're done: reached desired caller after skipping.
  3706         break;
  3708       caller_jvms = caller_jvms->caller();
  3709       --inlining_depth;
  3710     } while (inlining_depth > 0);
  3713   if (inlining_depth == 0) {
  3714 #ifndef PRODUCT
  3715     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3716       tty->print_cr("  Bailing out because caller depth (%d) exceeded inlining depth (%d)", caller_depth_type->get_con(), _depth);
  3717       tty->print_cr("  JVM state at this point:");
  3718       for (int i = _depth; i >= 1; i--) {
  3719         tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
  3722 #endif
  3723     return false; // Reached end of inlining
  3726   // Acquire method holder as java.lang.Class
  3727   ciInstanceKlass* caller_klass  = caller_jvms->method()->holder();
  3728   ciInstance*      caller_mirror = caller_klass->java_mirror();
  3729   // Push this as a constant
  3730   push(makecon(TypeInstPtr::make(caller_mirror)));
  3731 #ifndef PRODUCT
  3732   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
  3733     tty->print_cr("  Succeeded: caller = %s.%s, caller depth = %d, depth = %d", caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), caller_depth_type->get_con(), _depth);
  3734     tty->print_cr("  JVM state at this point:");
  3735     for (int i = _depth; i >= 1; i--) {
  3736       tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
  3739 #endif
  3740   return true;
  3743 // Helper routine for above
  3744 bool LibraryCallKit::is_method_invoke_or_aux_frame(JVMState* jvms) {
  3745   ciMethod* method = jvms->method();
  3747   // Is this the Method.invoke method itself?
  3748   if (method->intrinsic_id() == vmIntrinsics::_invoke)
  3749     return true;
  3751   // Is this a helper, defined somewhere underneath MethodAccessorImpl.
  3752   ciKlass* k = method->holder();
  3753   if (k->is_instance_klass()) {
  3754     ciInstanceKlass* ik = k->as_instance_klass();
  3755     for (; ik != NULL; ik = ik->super()) {
  3756       if (ik->name() == ciSymbol::sun_reflect_MethodAccessorImpl() &&
  3757           ik == env()->find_system_klass(ik->name())) {
  3758         return true;
  3762   else if (method->is_method_handle_adapter()) {
  3763     // This is an internal adapter frame from the MethodHandleCompiler -- skip it
  3764     return true;
  3767   return false;
  3770 static int value_field_offset = -1;  // offset of the "value" field of AtomicLongCSImpl.  This is needed by
  3771                                      // inline_native_AtomicLong_attemptUpdate() but it has no way of
  3772                                      // computing it since there is no lookup field by name function in the
  3773                                      // CI interface.  This is computed and set by inline_native_AtomicLong_get().
  3774                                      // Using a static variable here is safe even if we have multiple compilation
  3775                                      // threads because the offset is constant.  At worst the same offset will be
  3776                                      // computed and  stored multiple
  3778 bool LibraryCallKit::inline_native_AtomicLong_get() {
  3779   // Restore the stack and pop off the argument
  3780   _sp+=1;
  3781   Node *obj = pop();
  3783   // get the offset of the "value" field. Since the CI interfaces
  3784   // does not provide a way to look up a field by name, we scan the bytecodes
  3785   // to get the field index.  We expect the first 2 instructions of the method
  3786   // to be:
  3787   //    0 aload_0
  3788   //    1 getfield "value"
  3789   ciMethod* method = callee();
  3790   if (value_field_offset == -1)
  3792     ciField* value_field;
  3793     ciBytecodeStream iter(method);
  3794     Bytecodes::Code bc = iter.next();
  3796     if ((bc != Bytecodes::_aload_0) &&
  3797               ((bc != Bytecodes::_aload) || (iter.get_index() != 0)))
  3798       return false;
  3799     bc = iter.next();
  3800     if (bc != Bytecodes::_getfield)
  3801       return false;
  3802     bool ignore;
  3803     value_field = iter.get_field(ignore);
  3804     value_field_offset = value_field->offset_in_bytes();
  3807   // Null check without removing any arguments.
  3808   _sp++;
  3809   obj = do_null_check(obj, T_OBJECT);
  3810   _sp--;
  3811   // Check for locking null object
  3812   if (stopped()) return true;
  3814   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
  3815   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
  3816   int alias_idx = C->get_alias_index(adr_type);
  3818   Node *result = _gvn.transform(new (C, 3) LoadLLockedNode(control(), memory(alias_idx), adr));
  3820   push_pair(result);
  3822   return true;
  3825 bool LibraryCallKit::inline_native_AtomicLong_attemptUpdate() {
  3826   // Restore the stack and pop off the arguments
  3827   _sp+=5;
  3828   Node *newVal = pop_pair();
  3829   Node *oldVal = pop_pair();
  3830   Node *obj = pop();
  3832   // we need the offset of the "value" field which was computed when
  3833   // inlining the get() method.  Give up if we don't have it.
  3834   if (value_field_offset == -1)
  3835     return false;
  3837   // Null check without removing any arguments.
  3838   _sp+=5;
  3839   obj = do_null_check(obj, T_OBJECT);
  3840   _sp-=5;
  3841   // Check for locking null object
  3842   if (stopped()) return true;
  3844   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
  3845   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
  3846   int alias_idx = C->get_alias_index(adr_type);
  3848   Node *cas = _gvn.transform(new (C, 5) StoreLConditionalNode(control(), memory(alias_idx), adr, newVal, oldVal));
  3849   Node *store_proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
  3850   set_memory(store_proj, alias_idx);
  3851   Node *bol = _gvn.transform( new (C, 2) BoolNode( cas, BoolTest::eq ) );
  3853   Node *result;
  3854   // CMove node is not used to be able fold a possible check code
  3855   // after attemptUpdate() call. This code could be transformed
  3856   // into CMove node by loop optimizations.
  3858     RegionNode *r = new (C, 3) RegionNode(3);
  3859     result = new (C, 3) PhiNode(r, TypeInt::BOOL);
  3861     Node *iff = create_and_xform_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
  3862     Node *iftrue = opt_iff(r, iff);
  3863     r->init_req(1, iftrue);
  3864     result->init_req(1, intcon(1));
  3865     result->init_req(2, intcon(0));
  3867     set_control(_gvn.transform(r));
  3868     record_for_igvn(r);
  3870     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3873   push(_gvn.transform(result));
  3874   return true;
  3877 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
  3878   // restore the arguments
  3879   _sp += arg_size();
  3881   switch (id) {
  3882   case vmIntrinsics::_floatToRawIntBits:
  3883     push(_gvn.transform( new (C, 2) MoveF2INode(pop())));
  3884     break;
  3886   case vmIntrinsics::_intBitsToFloat:
  3887     push(_gvn.transform( new (C, 2) MoveI2FNode(pop())));
  3888     break;
  3890   case vmIntrinsics::_doubleToRawLongBits:
  3891     push_pair(_gvn.transform( new (C, 2) MoveD2LNode(pop_pair())));
  3892     break;
  3894   case vmIntrinsics::_longBitsToDouble:
  3895     push_pair(_gvn.transform( new (C, 2) MoveL2DNode(pop_pair())));
  3896     break;
  3898   case vmIntrinsics::_doubleToLongBits: {
  3899     Node* value = pop_pair();
  3901     // two paths (plus control) merge in a wood
  3902     RegionNode *r = new (C, 3) RegionNode(3);
  3903     Node *phi = new (C, 3) PhiNode(r, TypeLong::LONG);
  3905     Node *cmpisnan = _gvn.transform( new (C, 3) CmpDNode(value, value));
  3906     // Build the boolean node
  3907     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
  3909     // Branch either way.
  3910     // NaN case is less traveled, which makes all the difference.
  3911     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  3912     Node *opt_isnan = _gvn.transform(ifisnan);
  3913     assert( opt_isnan->is_If(), "Expect an IfNode");
  3914     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  3915     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
  3917     set_control(iftrue);
  3919     static const jlong nan_bits = CONST64(0x7ff8000000000000);
  3920     Node *slow_result = longcon(nan_bits); // return NaN
  3921     phi->init_req(1, _gvn.transform( slow_result ));
  3922     r->init_req(1, iftrue);
  3924     // Else fall through
  3925     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
  3926     set_control(iffalse);
  3928     phi->init_req(2, _gvn.transform( new (C, 2) MoveD2LNode(value)));
  3929     r->init_req(2, iffalse);
  3931     // Post merge
  3932     set_control(_gvn.transform(r));
  3933     record_for_igvn(r);
  3935     Node* result = _gvn.transform(phi);
  3936     assert(result->bottom_type()->isa_long(), "must be");
  3937     push_pair(result);
  3939     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3941     break;
  3944   case vmIntrinsics::_floatToIntBits: {
  3945     Node* value = pop();
  3947     // two paths (plus control) merge in a wood
  3948     RegionNode *r = new (C, 3) RegionNode(3);
  3949     Node *phi = new (C, 3) PhiNode(r, TypeInt::INT);
  3951     Node *cmpisnan = _gvn.transform( new (C, 3) CmpFNode(value, value));
  3952     // Build the boolean node
  3953     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
  3955     // Branch either way.
  3956     // NaN case is less traveled, which makes all the difference.
  3957     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
  3958     Node *opt_isnan = _gvn.transform(ifisnan);
  3959     assert( opt_isnan->is_If(), "Expect an IfNode");
  3960     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
  3961     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
  3963     set_control(iftrue);
  3965     static const jint nan_bits = 0x7fc00000;
  3966     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
  3967     phi->init_req(1, _gvn.transform( slow_result ));
  3968     r->init_req(1, iftrue);
  3970     // Else fall through
  3971     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
  3972     set_control(iffalse);
  3974     phi->init_req(2, _gvn.transform( new (C, 2) MoveF2INode(value)));
  3975     r->init_req(2, iffalse);
  3977     // Post merge
  3978     set_control(_gvn.transform(r));
  3979     record_for_igvn(r);
  3981     Node* result = _gvn.transform(phi);
  3982     assert(result->bottom_type()->isa_int(), "must be");
  3983     push(result);
  3985     C->set_has_split_ifs(true); // Has chance for split-if optimization
  3987     break;
  3990   default:
  3991     ShouldNotReachHere();
  3994   return true;
  3997 #ifdef _LP64
  3998 #define XTOP ,top() /*additional argument*/
  3999 #else  //_LP64
  4000 #define XTOP        /*no additional argument*/
  4001 #endif //_LP64
  4003 //----------------------inline_unsafe_copyMemory-------------------------
  4004 bool LibraryCallKit::inline_unsafe_copyMemory() {
  4005   if (callee()->is_static())  return false;  // caller must have the capability!
  4006   int nargs = 1 + 5 + 3;  // 5 args:  (src: ptr,off, dst: ptr,off, size)
  4007   assert(signature()->size() == nargs-1, "copy has 5 arguments");
  4008   null_check_receiver(callee());  // check then ignore argument(0)
  4009   if (stopped())  return true;
  4011   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
  4013   Node* src_ptr = argument(1);
  4014   Node* src_off = ConvL2X(argument(2));
  4015   assert(argument(3)->is_top(), "2nd half of long");
  4016   Node* dst_ptr = argument(4);
  4017   Node* dst_off = ConvL2X(argument(5));
  4018   assert(argument(6)->is_top(), "2nd half of long");
  4019   Node* size    = ConvL2X(argument(7));
  4020   assert(argument(8)->is_top(), "2nd half of long");
  4022   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
  4023          "fieldOffset must be byte-scaled");
  4025   Node* src = make_unsafe_address(src_ptr, src_off);
  4026   Node* dst = make_unsafe_address(dst_ptr, dst_off);
  4028   // Conservatively insert a memory barrier on all memory slices.
  4029   // Do not let writes of the copy source or destination float below the copy.
  4030   insert_mem_bar(Op_MemBarCPUOrder);
  4032   // Call it.  Note that the length argument is not scaled.
  4033   make_runtime_call(RC_LEAF|RC_NO_FP,
  4034                     OptoRuntime::fast_arraycopy_Type(),
  4035                     StubRoutines::unsafe_arraycopy(),
  4036                     "unsafe_arraycopy",
  4037                     TypeRawPtr::BOTTOM,
  4038                     src, dst, size XTOP);
  4040   // Do not let reads of the copy destination float above the copy.
  4041   insert_mem_bar(Op_MemBarCPUOrder);
  4043   return true;
  4046 //------------------------clone_coping-----------------------------------
  4047 // Helper function for inline_native_clone.
  4048 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
  4049   assert(obj_size != NULL, "");
  4050   Node* raw_obj = alloc_obj->in(1);
  4051   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
  4053   if (ReduceBulkZeroing) {
  4054     // We will be completely responsible for initializing this object -
  4055     // mark Initialize node as complete.
  4056     AllocateNode* alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
  4057     // The object was just allocated - there should be no any stores!
  4058     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
  4061   // Copy the fastest available way.
  4062   // TODO: generate fields copies for small objects instead.
  4063   Node* src  = obj;
  4064   Node* dest = alloc_obj;
  4065   Node* size = _gvn.transform(obj_size);
  4067   // Exclude the header but include array length to copy by 8 bytes words.
  4068   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
  4069   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
  4070                             instanceOopDesc::base_offset_in_bytes();
  4071   // base_off:
  4072   // 8  - 32-bit VM
  4073   // 12 - 64-bit VM, compressed oops
  4074   // 16 - 64-bit VM, normal oops
  4075   if (base_off % BytesPerLong != 0) {
  4076     assert(UseCompressedOops, "");
  4077     if (is_array) {
  4078       // Exclude length to copy by 8 bytes words.
  4079       base_off += sizeof(int);
  4080     } else {
  4081       // Include klass to copy by 8 bytes words.
  4082       base_off = instanceOopDesc::klass_offset_in_bytes();
  4084     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
  4086   src  = basic_plus_adr(src,  base_off);
  4087   dest = basic_plus_adr(dest, base_off);
  4089   // Compute the length also, if needed:
  4090   Node* countx = size;
  4091   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(base_off)) );
  4092   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong) ));
  4094   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  4095   bool disjoint_bases = true;
  4096   generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,
  4097                                src, NULL, dest, NULL, countx,
  4098                                /*dest_uninitialized*/true);
  4100   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
  4101   if (card_mark) {
  4102     assert(!is_array, "");
  4103     // Put in store barrier for any and all oops we are sticking
  4104     // into this object.  (We could avoid this if we could prove
  4105     // that the object type contains no oop fields at all.)
  4106     Node* no_particular_value = NULL;
  4107     Node* no_particular_field = NULL;
  4108     int raw_adr_idx = Compile::AliasIdxRaw;
  4109     post_barrier(control(),
  4110                  memory(raw_adr_type),
  4111                  alloc_obj,
  4112                  no_particular_field,
  4113                  raw_adr_idx,
  4114                  no_particular_value,
  4115                  T_OBJECT,
  4116                  false);
  4119   // Do not let reads from the cloned object float above the arraycopy.
  4120   insert_mem_bar(Op_MemBarCPUOrder);
  4123 //------------------------inline_native_clone----------------------------
  4124 // Here are the simple edge cases:
  4125 //  null receiver => normal trap
  4126 //  virtual and clone was overridden => slow path to out-of-line clone
  4127 //  not cloneable or finalizer => slow path to out-of-line Object.clone
  4128 //
  4129 // The general case has two steps, allocation and copying.
  4130 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
  4131 //
  4132 // Copying also has two cases, oop arrays and everything else.
  4133 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
  4134 // Everything else uses the tight inline loop supplied by CopyArrayNode.
  4135 //
  4136 // These steps fold up nicely if and when the cloned object's klass
  4137 // can be sharply typed as an object array, a type array, or an instance.
  4138 //
  4139 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
  4140   int nargs = 1;
  4141   PhiNode* result_val;
  4143   //set the original stack and the reexecute bit for the interpreter to reexecute
  4144   //the bytecode that invokes Object.clone if deoptimization happens
  4145   { PreserveReexecuteState preexecs(this);
  4146     jvms()->set_should_reexecute(true);
  4148     //null_check_receiver will adjust _sp (push and pop)
  4149     Node* obj = null_check_receiver(callee());
  4150     if (stopped())  return true;
  4152     _sp += nargs;
  4154     Node* obj_klass = load_object_klass(obj);
  4155     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
  4156     const TypeOopPtr*   toop   = ((tklass != NULL)
  4157                                 ? tklass->as_instance_type()
  4158                                 : TypeInstPtr::NOTNULL);
  4160     // Conservatively insert a memory barrier on all memory slices.
  4161     // Do not let writes into the original float below the clone.
  4162     insert_mem_bar(Op_MemBarCPUOrder);
  4164     // paths into result_reg:
  4165     enum {
  4166       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
  4167       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
  4168       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
  4169       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
  4170       PATH_LIMIT
  4171     };
  4172     RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  4173     result_val             = new(C, PATH_LIMIT) PhiNode(result_reg,
  4174                                                         TypeInstPtr::NOTNULL);
  4175     PhiNode*    result_i_o = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
  4176     PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
  4177                                                         TypePtr::BOTTOM);
  4178     record_for_igvn(result_reg);
  4180     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
  4181     int raw_adr_idx = Compile::AliasIdxRaw;
  4182     const bool raw_mem_only = true;
  4185     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
  4186     if (array_ctl != NULL) {
  4187       // It's an array.
  4188       PreserveJVMState pjvms(this);
  4189       set_control(array_ctl);
  4190       Node* obj_length = load_array_length(obj);
  4191       Node* obj_size  = NULL;
  4192       Node* alloc_obj = new_array(obj_klass, obj_length, 0,
  4193                                   raw_mem_only, &obj_size);
  4195       if (!use_ReduceInitialCardMarks()) {
  4196         // If it is an oop array, it requires very special treatment,
  4197         // because card marking is required on each card of the array.
  4198         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
  4199         if (is_obja != NULL) {
  4200           PreserveJVMState pjvms2(this);
  4201           set_control(is_obja);
  4202           // Generate a direct call to the right arraycopy function(s).
  4203           bool disjoint_bases = true;
  4204           bool length_never_negative = true;
  4205           generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
  4206                              obj, intcon(0), alloc_obj, intcon(0),
  4207                              obj_length,
  4208                              disjoint_bases, length_never_negative);
  4209           result_reg->init_req(_objArray_path, control());
  4210           result_val->init_req(_objArray_path, alloc_obj);
  4211           result_i_o ->set_req(_objArray_path, i_o());
  4212           result_mem ->set_req(_objArray_path, reset_memory());
  4215       // Otherwise, there are no card marks to worry about.
  4216       // (We can dispense with card marks if we know the allocation
  4217       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
  4218       //  causes the non-eden paths to take compensating steps to
  4219       //  simulate a fresh allocation, so that no further
  4220       //  card marks are required in compiled code to initialize
  4221       //  the object.)
  4223       if (!stopped()) {
  4224         copy_to_clone(obj, alloc_obj, obj_size, true, false);
  4226         // Present the results of the copy.
  4227         result_reg->init_req(_array_path, control());
  4228         result_val->init_req(_array_path, alloc_obj);
  4229         result_i_o ->set_req(_array_path, i_o());
  4230         result_mem ->set_req(_array_path, reset_memory());
  4234     // We only go to the instance fast case code if we pass a number of guards.
  4235     // The paths which do not pass are accumulated in the slow_region.
  4236     RegionNode* slow_region = new (C, 1) RegionNode(1);
  4237     record_for_igvn(slow_region);
  4238     if (!stopped()) {
  4239       // It's an instance (we did array above).  Make the slow-path tests.
  4240       // If this is a virtual call, we generate a funny guard.  We grab
  4241       // the vtable entry corresponding to clone() from the target object.
  4242       // If the target method which we are calling happens to be the
  4243       // Object clone() method, we pass the guard.  We do not need this
  4244       // guard for non-virtual calls; the caller is known to be the native
  4245       // Object clone().
  4246       if (is_virtual) {
  4247         generate_virtual_guard(obj_klass, slow_region);
  4250       // The object must be cloneable and must not have a finalizer.
  4251       // Both of these conditions may be checked in a single test.
  4252       // We could optimize the cloneable test further, but we don't care.
  4253       generate_access_flags_guard(obj_klass,
  4254                                   // Test both conditions:
  4255                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
  4256                                   // Must be cloneable but not finalizer:
  4257                                   JVM_ACC_IS_CLONEABLE,
  4258                                   slow_region);
  4261     if (!stopped()) {
  4262       // It's an instance, and it passed the slow-path tests.
  4263       PreserveJVMState pjvms(this);
  4264       Node* obj_size  = NULL;
  4265       Node* alloc_obj = new_instance(obj_klass, NULL, raw_mem_only, &obj_size);
  4267       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
  4269       // Present the results of the slow call.
  4270       result_reg->init_req(_instance_path, control());
  4271       result_val->init_req(_instance_path, alloc_obj);
  4272       result_i_o ->set_req(_instance_path, i_o());
  4273       result_mem ->set_req(_instance_path, reset_memory());
  4276     // Generate code for the slow case.  We make a call to clone().
  4277     set_control(_gvn.transform(slow_region));
  4278     if (!stopped()) {
  4279       PreserveJVMState pjvms(this);
  4280       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
  4281       Node* slow_result = set_results_for_java_call(slow_call);
  4282       // this->control() comes from set_results_for_java_call
  4283       result_reg->init_req(_slow_path, control());
  4284       result_val->init_req(_slow_path, slow_result);
  4285       result_i_o ->set_req(_slow_path, i_o());
  4286       result_mem ->set_req(_slow_path, reset_memory());
  4289     // Return the combined state.
  4290     set_control(    _gvn.transform(result_reg) );
  4291     set_i_o(        _gvn.transform(result_i_o) );
  4292     set_all_memory( _gvn.transform(result_mem) );
  4293   } //original reexecute and sp are set back here
  4295   push(_gvn.transform(result_val));
  4297   return true;
  4301 // constants for computing the copy function
  4302 enum {
  4303   COPYFUNC_UNALIGNED = 0,
  4304   COPYFUNC_ALIGNED = 1,                 // src, dest aligned to HeapWordSize
  4305   COPYFUNC_CONJOINT = 0,
  4306   COPYFUNC_DISJOINT = 2                 // src != dest, or transfer can descend
  4307 };
  4309 // Note:  The condition "disjoint" applies also for overlapping copies
  4310 // where an descending copy is permitted (i.e., dest_offset <= src_offset).
  4311 static address
  4312 select_arraycopy_function(BasicType t, bool aligned, bool disjoint, const char* &name, bool dest_uninitialized) {
  4313   int selector =
  4314     (aligned  ? COPYFUNC_ALIGNED  : COPYFUNC_UNALIGNED) +
  4315     (disjoint ? COPYFUNC_DISJOINT : COPYFUNC_CONJOINT);
  4317 #define RETURN_STUB(xxx_arraycopy) { \
  4318   name = #xxx_arraycopy; \
  4319   return StubRoutines::xxx_arraycopy(); }
  4321 #define RETURN_STUB_PARM(xxx_arraycopy, parm) {           \
  4322   name = #xxx_arraycopy; \
  4323   return StubRoutines::xxx_arraycopy(parm); }
  4325   switch (t) {
  4326   case T_BYTE:
  4327   case T_BOOLEAN:
  4328     switch (selector) {
  4329     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_arraycopy);
  4330     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_arraycopy);
  4331     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_disjoint_arraycopy);
  4332     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_disjoint_arraycopy);
  4334   case T_CHAR:
  4335   case T_SHORT:
  4336     switch (selector) {
  4337     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_arraycopy);
  4338     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_arraycopy);
  4339     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_disjoint_arraycopy);
  4340     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_disjoint_arraycopy);
  4342   case T_INT:
  4343   case T_FLOAT:
  4344     switch (selector) {
  4345     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_arraycopy);
  4346     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_arraycopy);
  4347     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_disjoint_arraycopy);
  4348     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_disjoint_arraycopy);
  4350   case T_DOUBLE:
  4351   case T_LONG:
  4352     switch (selector) {
  4353     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_arraycopy);
  4354     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_arraycopy);
  4355     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_disjoint_arraycopy);
  4356     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_disjoint_arraycopy);
  4358   case T_ARRAY:
  4359   case T_OBJECT:
  4360     switch (selector) {
  4361     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB_PARM(oop_arraycopy, dest_uninitialized);
  4362     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB_PARM(arrayof_oop_arraycopy, dest_uninitialized);
  4363     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB_PARM(oop_disjoint_arraycopy, dest_uninitialized);
  4364     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB_PARM(arrayof_oop_disjoint_arraycopy, dest_uninitialized);
  4366   default:
  4367     ShouldNotReachHere();
  4368     return NULL;
  4371 #undef RETURN_STUB
  4372 #undef RETURN_STUB_PARM
  4375 //------------------------------basictype2arraycopy----------------------------
  4376 address LibraryCallKit::basictype2arraycopy(BasicType t,
  4377                                             Node* src_offset,
  4378                                             Node* dest_offset,
  4379                                             bool disjoint_bases,
  4380                                             const char* &name,
  4381                                             bool dest_uninitialized) {
  4382   const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
  4383   const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
  4385   bool aligned = false;
  4386   bool disjoint = disjoint_bases;
  4388   // if the offsets are the same, we can treat the memory regions as
  4389   // disjoint, because either the memory regions are in different arrays,
  4390   // or they are identical (which we can treat as disjoint.)  We can also
  4391   // treat a copy with a destination index  less that the source index
  4392   // as disjoint since a low->high copy will work correctly in this case.
  4393   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
  4394       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
  4395     // both indices are constants
  4396     int s_offs = src_offset_inttype->get_con();
  4397     int d_offs = dest_offset_inttype->get_con();
  4398     int element_size = type2aelembytes(t);
  4399     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
  4400               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
  4401     if (s_offs >= d_offs)  disjoint = true;
  4402   } else if (src_offset == dest_offset && src_offset != NULL) {
  4403     // This can occur if the offsets are identical non-constants.
  4404     disjoint = true;
  4407   return select_arraycopy_function(t, aligned, disjoint, name, dest_uninitialized);
  4411 //------------------------------inline_arraycopy-----------------------
  4412 bool LibraryCallKit::inline_arraycopy() {
  4413   // Restore the stack and pop off the arguments.
  4414   int nargs = 5;  // 2 oops, 3 ints, no size_t or long
  4415   assert(callee()->signature()->size() == nargs, "copy has 5 arguments");
  4417   Node *src         = argument(0);
  4418   Node *src_offset  = argument(1);
  4419   Node *dest        = argument(2);
  4420   Node *dest_offset = argument(3);
  4421   Node *length      = argument(4);
  4423   // Compile time checks.  If any of these checks cannot be verified at compile time,
  4424   // we do not make a fast path for this call.  Instead, we let the call remain as it
  4425   // is.  The checks we choose to mandate at compile time are:
  4426   //
  4427   // (1) src and dest are arrays.
  4428   const Type* src_type = src->Value(&_gvn);
  4429   const Type* dest_type = dest->Value(&_gvn);
  4430   const TypeAryPtr* top_src = src_type->isa_aryptr();
  4431   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
  4432   if (top_src  == NULL || top_src->klass()  == NULL ||
  4433       top_dest == NULL || top_dest->klass() == NULL) {
  4434     // Conservatively insert a memory barrier on all memory slices.
  4435     // Do not let writes into the source float below the arraycopy.
  4436     insert_mem_bar(Op_MemBarCPUOrder);
  4438     // Call StubRoutines::generic_arraycopy stub.
  4439     generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,
  4440                        src, src_offset, dest, dest_offset, length);
  4442     // Do not let reads from the destination float above the arraycopy.
  4443     // Since we cannot type the arrays, we don't know which slices
  4444     // might be affected.  We could restrict this barrier only to those
  4445     // memory slices which pertain to array elements--but don't bother.
  4446     if (!InsertMemBarAfterArraycopy)
  4447       // (If InsertMemBarAfterArraycopy, there is already one in place.)
  4448       insert_mem_bar(Op_MemBarCPUOrder);
  4449     return true;
  4452   // (2) src and dest arrays must have elements of the same BasicType
  4453   // Figure out the size and type of the elements we will be copying.
  4454   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
  4455   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
  4456   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
  4457   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
  4459   if (src_elem != dest_elem || dest_elem == T_VOID) {
  4460     // The component types are not the same or are not recognized.  Punt.
  4461     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
  4462     generate_slow_arraycopy(TypePtr::BOTTOM,
  4463                             src, src_offset, dest, dest_offset, length,
  4464                             /*dest_uninitialized*/false);
  4465     return true;
  4468   //---------------------------------------------------------------------------
  4469   // We will make a fast path for this call to arraycopy.
  4471   // We have the following tests left to perform:
  4472   //
  4473   // (3) src and dest must not be null.
  4474   // (4) src_offset must not be negative.
  4475   // (5) dest_offset must not be negative.
  4476   // (6) length must not be negative.
  4477   // (7) src_offset + length must not exceed length of src.
  4478   // (8) dest_offset + length must not exceed length of dest.
  4479   // (9) each element of an oop array must be assignable
  4481   RegionNode* slow_region = new (C, 1) RegionNode(1);
  4482   record_for_igvn(slow_region);
  4484   // (3) operands must not be null
  4485   // We currently perform our null checks with the do_null_check routine.
  4486   // This means that the null exceptions will be reported in the caller
  4487   // rather than (correctly) reported inside of the native arraycopy call.
  4488   // This should be corrected, given time.  We do our null check with the
  4489   // stack pointer restored.
  4490   _sp += nargs;
  4491   src  = do_null_check(src,  T_ARRAY);
  4492   dest = do_null_check(dest, T_ARRAY);
  4493   _sp -= nargs;
  4495   // (4) src_offset must not be negative.
  4496   generate_negative_guard(src_offset, slow_region);
  4498   // (5) dest_offset must not be negative.
  4499   generate_negative_guard(dest_offset, slow_region);
  4501   // (6) length must not be negative (moved to generate_arraycopy()).
  4502   // generate_negative_guard(length, slow_region);
  4504   // (7) src_offset + length must not exceed length of src.
  4505   generate_limit_guard(src_offset, length,
  4506                        load_array_length(src),
  4507                        slow_region);
  4509   // (8) dest_offset + length must not exceed length of dest.
  4510   generate_limit_guard(dest_offset, length,
  4511                        load_array_length(dest),
  4512                        slow_region);
  4514   // (9) each element of an oop array must be assignable
  4515   // The generate_arraycopy subroutine checks this.
  4517   // This is where the memory effects are placed:
  4518   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
  4519   generate_arraycopy(adr_type, dest_elem,
  4520                      src, src_offset, dest, dest_offset, length,
  4521                      false, false, slow_region);
  4523   return true;
  4526 //-----------------------------generate_arraycopy----------------------
  4527 // Generate an optimized call to arraycopy.
  4528 // Caller must guard against non-arrays.
  4529 // Caller must determine a common array basic-type for both arrays.
  4530 // Caller must validate offsets against array bounds.
  4531 // The slow_region has already collected guard failure paths
  4532 // (such as out of bounds length or non-conformable array types).
  4533 // The generated code has this shape, in general:
  4534 //
  4535 //     if (length == 0)  return   // via zero_path
  4536 //     slowval = -1
  4537 //     if (types unknown) {
  4538 //       slowval = call generic copy loop
  4539 //       if (slowval == 0)  return  // via checked_path
  4540 //     } else if (indexes in bounds) {
  4541 //       if ((is object array) && !(array type check)) {
  4542 //         slowval = call checked copy loop
  4543 //         if (slowval == 0)  return  // via checked_path
  4544 //       } else {
  4545 //         call bulk copy loop
  4546 //         return  // via fast_path
  4547 //       }
  4548 //     }
  4549 //     // adjust params for remaining work:
  4550 //     if (slowval != -1) {
  4551 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
  4552 //     }
  4553 //   slow_region:
  4554 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
  4555 //     return  // via slow_call_path
  4556 //
  4557 // This routine is used from several intrinsics:  System.arraycopy,
  4558 // Object.clone (the array subcase), and Arrays.copyOf[Range].
  4559 //
  4560 void
  4561 LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,
  4562                                    BasicType basic_elem_type,
  4563                                    Node* src,  Node* src_offset,
  4564                                    Node* dest, Node* dest_offset,
  4565                                    Node* copy_length,
  4566                                    bool disjoint_bases,
  4567                                    bool length_never_negative,
  4568                                    RegionNode* slow_region) {
  4570   if (slow_region == NULL) {
  4571     slow_region = new(C,1) RegionNode(1);
  4572     record_for_igvn(slow_region);
  4575   Node* original_dest      = dest;
  4576   AllocateArrayNode* alloc = NULL;  // used for zeroing, if needed
  4577   bool  dest_uninitialized = false;
  4579   // See if this is the initialization of a newly-allocated array.
  4580   // If so, we will take responsibility here for initializing it to zero.
  4581   // (Note:  Because tightly_coupled_allocation performs checks on the
  4582   // out-edges of the dest, we need to avoid making derived pointers
  4583   // from it until we have checked its uses.)
  4584   if (ReduceBulkZeroing
  4585       && !ZeroTLAB              // pointless if already zeroed
  4586       && basic_elem_type != T_CONFLICT // avoid corner case
  4587       && !_gvn.eqv_uncast(src, dest)
  4588       && ((alloc = tightly_coupled_allocation(dest, slow_region))
  4589           != NULL)
  4590       && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
  4591       && alloc->maybe_set_complete(&_gvn)) {
  4592     // "You break it, you buy it."
  4593     InitializeNode* init = alloc->initialization();
  4594     assert(init->is_complete(), "we just did this");
  4595     assert(dest->is_CheckCastPP(), "sanity");
  4596     assert(dest->in(0)->in(0) == init, "dest pinned");
  4597     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
  4598     // From this point on, every exit path is responsible for
  4599     // initializing any non-copied parts of the object to zero.
  4600     // Also, if this flag is set we make sure that arraycopy interacts properly
  4601     // with G1, eliding pre-barriers. See CR 6627983.
  4602     dest_uninitialized = true;
  4603   } else {
  4604     // No zeroing elimination here.
  4605     alloc             = NULL;
  4606     //original_dest   = dest;
  4607     //dest_uninitialized = false;
  4610   // Results are placed here:
  4611   enum { fast_path        = 1,  // normal void-returning assembly stub
  4612          checked_path     = 2,  // special assembly stub with cleanup
  4613          slow_call_path   = 3,  // something went wrong; call the VM
  4614          zero_path        = 4,  // bypass when length of copy is zero
  4615          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
  4616          PATH_LIMIT       = 6
  4617   };
  4618   RegionNode* result_region = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
  4619   PhiNode*    result_i_o    = new(C, PATH_LIMIT) PhiNode(result_region, Type::ABIO);
  4620   PhiNode*    result_memory = new(C, PATH_LIMIT) PhiNode(result_region, Type::MEMORY, adr_type);
  4621   record_for_igvn(result_region);
  4622   _gvn.set_type_bottom(result_i_o);
  4623   _gvn.set_type_bottom(result_memory);
  4624   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
  4626   // The slow_control path:
  4627   Node* slow_control;
  4628   Node* slow_i_o = i_o();
  4629   Node* slow_mem = memory(adr_type);
  4630   debug_only(slow_control = (Node*) badAddress);
  4632   // Checked control path:
  4633   Node* checked_control = top();
  4634   Node* checked_mem     = NULL;
  4635   Node* checked_i_o     = NULL;
  4636   Node* checked_value   = NULL;
  4638   if (basic_elem_type == T_CONFLICT) {
  4639     assert(!dest_uninitialized, "");
  4640     Node* cv = generate_generic_arraycopy(adr_type,
  4641                                           src, src_offset, dest, dest_offset,
  4642                                           copy_length, dest_uninitialized);
  4643     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  4644     checked_control = control();
  4645     checked_i_o     = i_o();
  4646     checked_mem     = memory(adr_type);
  4647     checked_value   = cv;
  4648     set_control(top());         // no fast path
  4651   Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);
  4652   if (not_pos != NULL) {
  4653     PreserveJVMState pjvms(this);
  4654     set_control(not_pos);
  4656     // (6) length must not be negative.
  4657     if (!length_never_negative) {
  4658       generate_negative_guard(copy_length, slow_region);
  4661     // copy_length is 0.
  4662     if (!stopped() && dest_uninitialized) {
  4663       Node* dest_length = alloc->in(AllocateNode::ALength);
  4664       if (_gvn.eqv_uncast(copy_length, dest_length)
  4665           || _gvn.find_int_con(dest_length, 1) <= 0) {
  4666         // There is no zeroing to do. No need for a secondary raw memory barrier.
  4667       } else {
  4668         // Clear the whole thing since there are no source elements to copy.
  4669         generate_clear_array(adr_type, dest, basic_elem_type,
  4670                              intcon(0), NULL,
  4671                              alloc->in(AllocateNode::AllocSize));
  4672         // Use a secondary InitializeNode as raw memory barrier.
  4673         // Currently it is needed only on this path since other
  4674         // paths have stub or runtime calls as raw memory barriers.
  4675         InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,
  4676                                                        Compile::AliasIdxRaw,
  4677                                                        top())->as_Initialize();
  4678         init->set_complete(&_gvn);  // (there is no corresponding AllocateNode)
  4682     // Present the results of the fast call.
  4683     result_region->init_req(zero_path, control());
  4684     result_i_o   ->init_req(zero_path, i_o());
  4685     result_memory->init_req(zero_path, memory(adr_type));
  4688   if (!stopped() && dest_uninitialized) {
  4689     // We have to initialize the *uncopied* part of the array to zero.
  4690     // The copy destination is the slice dest[off..off+len].  The other slices
  4691     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
  4692     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
  4693     Node* dest_length = alloc->in(AllocateNode::ALength);
  4694     Node* dest_tail   = _gvn.transform( new(C,3) AddINode(dest_offset,
  4695                                                           copy_length) );
  4697     // If there is a head section that needs zeroing, do it now.
  4698     if (find_int_con(dest_offset, -1) != 0) {
  4699       generate_clear_array(adr_type, dest, basic_elem_type,
  4700                            intcon(0), dest_offset,
  4701                            NULL);
  4704     // Next, perform a dynamic check on the tail length.
  4705     // It is often zero, and we can win big if we prove this.
  4706     // There are two wins:  Avoid generating the ClearArray
  4707     // with its attendant messy index arithmetic, and upgrade
  4708     // the copy to a more hardware-friendly word size of 64 bits.
  4709     Node* tail_ctl = NULL;
  4710     if (!stopped() && !_gvn.eqv_uncast(dest_tail, dest_length)) {
  4711       Node* cmp_lt   = _gvn.transform( new(C,3) CmpINode(dest_tail, dest_length) );
  4712       Node* bol_lt   = _gvn.transform( new(C,2) BoolNode(cmp_lt, BoolTest::lt) );
  4713       tail_ctl = generate_slow_guard(bol_lt, NULL);
  4714       assert(tail_ctl != NULL || !stopped(), "must be an outcome");
  4717     // At this point, let's assume there is no tail.
  4718     if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {
  4719       // There is no tail.  Try an upgrade to a 64-bit copy.
  4720       bool didit = false;
  4721       { PreserveJVMState pjvms(this);
  4722         didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,
  4723                                          src, src_offset, dest, dest_offset,
  4724                                          dest_size, dest_uninitialized);
  4725         if (didit) {
  4726           // Present the results of the block-copying fast call.
  4727           result_region->init_req(bcopy_path, control());
  4728           result_i_o   ->init_req(bcopy_path, i_o());
  4729           result_memory->init_req(bcopy_path, memory(adr_type));
  4732       if (didit)
  4733         set_control(top());     // no regular fast path
  4736     // Clear the tail, if any.
  4737     if (tail_ctl != NULL) {
  4738       Node* notail_ctl = stopped() ? NULL : control();
  4739       set_control(tail_ctl);
  4740       if (notail_ctl == NULL) {
  4741         generate_clear_array(adr_type, dest, basic_elem_type,
  4742                              dest_tail, NULL,
  4743                              dest_size);
  4744       } else {
  4745         // Make a local merge.
  4746         Node* done_ctl = new(C,3) RegionNode(3);
  4747         Node* done_mem = new(C,3) PhiNode(done_ctl, Type::MEMORY, adr_type);
  4748         done_ctl->init_req(1, notail_ctl);
  4749         done_mem->init_req(1, memory(adr_type));
  4750         generate_clear_array(adr_type, dest, basic_elem_type,
  4751                              dest_tail, NULL,
  4752                              dest_size);
  4753         done_ctl->init_req(2, control());
  4754         done_mem->init_req(2, memory(adr_type));
  4755         set_control( _gvn.transform(done_ctl) );
  4756         set_memory(  _gvn.transform(done_mem), adr_type );
  4761   BasicType copy_type = basic_elem_type;
  4762   assert(basic_elem_type != T_ARRAY, "caller must fix this");
  4763   if (!stopped() && copy_type == T_OBJECT) {
  4764     // If src and dest have compatible element types, we can copy bits.
  4765     // Types S[] and D[] are compatible if D is a supertype of S.
  4766     //
  4767     // If they are not, we will use checked_oop_disjoint_arraycopy,
  4768     // which performs a fast optimistic per-oop check, and backs off
  4769     // further to JVM_ArrayCopy on the first per-oop check that fails.
  4770     // (Actually, we don't move raw bits only; the GC requires card marks.)
  4772     // Get the klassOop for both src and dest
  4773     Node* src_klass  = load_object_klass(src);
  4774     Node* dest_klass = load_object_klass(dest);
  4776     // Generate the subtype check.
  4777     // This might fold up statically, or then again it might not.
  4778     //
  4779     // Non-static example:  Copying List<String>.elements to a new String[].
  4780     // The backing store for a List<String> is always an Object[],
  4781     // but its elements are always type String, if the generic types
  4782     // are correct at the source level.
  4783     //
  4784     // Test S[] against D[], not S against D, because (probably)
  4785     // the secondary supertype cache is less busy for S[] than S.
  4786     // This usually only matters when D is an interface.
  4787     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
  4788     // Plug failing path into checked_oop_disjoint_arraycopy
  4789     if (not_subtype_ctrl != top()) {
  4790       PreserveJVMState pjvms(this);
  4791       set_control(not_subtype_ctrl);
  4792       // (At this point we can assume disjoint_bases, since types differ.)
  4793       int ek_offset = objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc);
  4794       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
  4795       Node* n1 = LoadKlassNode::make(_gvn, immutable_memory(), p1, TypeRawPtr::BOTTOM);
  4796       Node* dest_elem_klass = _gvn.transform(n1);
  4797       Node* cv = generate_checkcast_arraycopy(adr_type,
  4798                                               dest_elem_klass,
  4799                                               src, src_offset, dest, dest_offset,
  4800                                               ConvI2X(copy_length), dest_uninitialized);
  4801       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
  4802       checked_control = control();
  4803       checked_i_o     = i_o();
  4804       checked_mem     = memory(adr_type);
  4805       checked_value   = cv;
  4807     // At this point we know we do not need type checks on oop stores.
  4809     // Let's see if we need card marks:
  4810     if (alloc != NULL && use_ReduceInitialCardMarks()) {
  4811       // If we do not need card marks, copy using the jint or jlong stub.
  4812       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
  4813       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
  4814              "sizes agree");
  4818   if (!stopped()) {
  4819     // Generate the fast path, if possible.
  4820     PreserveJVMState pjvms(this);
  4821     generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,
  4822                                  src, src_offset, dest, dest_offset,
  4823                                  ConvI2X(copy_length), dest_uninitialized);
  4825     // Present the results of the fast call.
  4826     result_region->init_req(fast_path, control());
  4827     result_i_o   ->init_req(fast_path, i_o());
  4828     result_memory->init_req(fast_path, memory(adr_type));
  4831   // Here are all the slow paths up to this point, in one bundle:
  4832   slow_control = top();
  4833   if (slow_region != NULL)
  4834     slow_control = _gvn.transform(slow_region);
  4835   debug_only(slow_region = (RegionNode*)badAddress);
  4837   set_control(checked_control);
  4838   if (!stopped()) {
  4839     // Clean up after the checked call.
  4840     // The returned value is either 0 or -1^K,
  4841     // where K = number of partially transferred array elements.
  4842     Node* cmp = _gvn.transform( new(C, 3) CmpINode(checked_value, intcon(0)) );
  4843     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::eq) );
  4844     IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
  4846     // If it is 0, we are done, so transfer to the end.
  4847     Node* checks_done = _gvn.transform( new(C, 1) IfTrueNode(iff) );
  4848     result_region->init_req(checked_path, checks_done);
  4849     result_i_o   ->init_req(checked_path, checked_i_o);
  4850     result_memory->init_req(checked_path, checked_mem);
  4852     // If it is not zero, merge into the slow call.
  4853     set_control( _gvn.transform( new(C, 1) IfFalseNode(iff) ));
  4854     RegionNode* slow_reg2 = new(C, 3) RegionNode(3);
  4855     PhiNode*    slow_i_o2 = new(C, 3) PhiNode(slow_reg2, Type::ABIO);
  4856     PhiNode*    slow_mem2 = new(C, 3) PhiNode(slow_reg2, Type::MEMORY, adr_type);
  4857     record_for_igvn(slow_reg2);
  4858     slow_reg2  ->init_req(1, slow_control);
  4859     slow_i_o2  ->init_req(1, slow_i_o);
  4860     slow_mem2  ->init_req(1, slow_mem);
  4861     slow_reg2  ->init_req(2, control());
  4862     slow_i_o2  ->init_req(2, checked_i_o);
  4863     slow_mem2  ->init_req(2, checked_mem);
  4865     slow_control = _gvn.transform(slow_reg2);
  4866     slow_i_o     = _gvn.transform(slow_i_o2);
  4867     slow_mem     = _gvn.transform(slow_mem2);
  4869     if (alloc != NULL) {
  4870       // We'll restart from the very beginning, after zeroing the whole thing.
  4871       // This can cause double writes, but that's OK since dest is brand new.
  4872       // So we ignore the low 31 bits of the value returned from the stub.
  4873     } else {
  4874       // We must continue the copy exactly where it failed, or else
  4875       // another thread might see the wrong number of writes to dest.
  4876       Node* checked_offset = _gvn.transform( new(C, 3) XorINode(checked_value, intcon(-1)) );
  4877       Node* slow_offset    = new(C, 3) PhiNode(slow_reg2, TypeInt::INT);
  4878       slow_offset->init_req(1, intcon(0));
  4879       slow_offset->init_req(2, checked_offset);
  4880       slow_offset  = _gvn.transform(slow_offset);
  4882       // Adjust the arguments by the conditionally incoming offset.
  4883       Node* src_off_plus  = _gvn.transform( new(C, 3) AddINode(src_offset,  slow_offset) );
  4884       Node* dest_off_plus = _gvn.transform( new(C, 3) AddINode(dest_offset, slow_offset) );
  4885       Node* length_minus  = _gvn.transform( new(C, 3) SubINode(copy_length, slow_offset) );
  4887       // Tweak the node variables to adjust the code produced below:
  4888       src_offset  = src_off_plus;
  4889       dest_offset = dest_off_plus;
  4890       copy_length = length_minus;
  4894   set_control(slow_control);
  4895   if (!stopped()) {
  4896     // Generate the slow path, if needed.
  4897     PreserveJVMState pjvms(this);   // replace_in_map may trash the map
  4899     set_memory(slow_mem, adr_type);
  4900     set_i_o(slow_i_o);
  4902     if (dest_uninitialized) {
  4903       generate_clear_array(adr_type, dest, basic_elem_type,
  4904                            intcon(0), NULL,
  4905                            alloc->in(AllocateNode::AllocSize));
  4908     generate_slow_arraycopy(adr_type,
  4909                             src, src_offset, dest, dest_offset,
  4910                             copy_length, /*dest_uninitialized*/false);
  4912     result_region->init_req(slow_call_path, control());
  4913     result_i_o   ->init_req(slow_call_path, i_o());
  4914     result_memory->init_req(slow_call_path, memory(adr_type));
  4917   // Remove unused edges.
  4918   for (uint i = 1; i < result_region->req(); i++) {
  4919     if (result_region->in(i) == NULL)
  4920       result_region->init_req(i, top());
  4923   // Finished; return the combined state.
  4924   set_control( _gvn.transform(result_region) );
  4925   set_i_o(     _gvn.transform(result_i_o)    );
  4926   set_memory(  _gvn.transform(result_memory), adr_type );
  4928   // The memory edges above are precise in order to model effects around
  4929   // array copies accurately to allow value numbering of field loads around
  4930   // arraycopy.  Such field loads, both before and after, are common in Java
  4931   // collections and similar classes involving header/array data structures.
  4932   //
  4933   // But with low number of register or when some registers are used or killed
  4934   // by arraycopy calls it causes registers spilling on stack. See 6544710.
  4935   // The next memory barrier is added to avoid it. If the arraycopy can be
  4936   // optimized away (which it can, sometimes) then we can manually remove
  4937   // the membar also.
  4938   //
  4939   // Do not let reads from the cloned object float above the arraycopy.
  4940   if (InsertMemBarAfterArraycopy || alloc != NULL)
  4941     insert_mem_bar(Op_MemBarCPUOrder);
  4945 // Helper function which determines if an arraycopy immediately follows
  4946 // an allocation, with no intervening tests or other escapes for the object.
  4947 AllocateArrayNode*
  4948 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
  4949                                            RegionNode* slow_region) {
  4950   if (stopped())             return NULL;  // no fast path
  4951   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
  4953   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
  4954   if (alloc == NULL)  return NULL;
  4956   Node* rawmem = memory(Compile::AliasIdxRaw);
  4957   // Is the allocation's memory state untouched?
  4958   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
  4959     // Bail out if there have been raw-memory effects since the allocation.
  4960     // (Example:  There might have been a call or safepoint.)
  4961     return NULL;
  4963   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
  4964   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
  4965     return NULL;
  4968   // There must be no unexpected observers of this allocation.
  4969   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
  4970     Node* obs = ptr->fast_out(i);
  4971     if (obs != this->map()) {
  4972       return NULL;
  4976   // This arraycopy must unconditionally follow the allocation of the ptr.
  4977   Node* alloc_ctl = ptr->in(0);
  4978   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
  4980   Node* ctl = control();
  4981   while (ctl != alloc_ctl) {
  4982     // There may be guards which feed into the slow_region.
  4983     // Any other control flow means that we might not get a chance
  4984     // to finish initializing the allocated object.
  4985     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
  4986       IfNode* iff = ctl->in(0)->as_If();
  4987       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
  4988       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
  4989       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
  4990         ctl = iff->in(0);       // This test feeds the known slow_region.
  4991         continue;
  4993       // One more try:  Various low-level checks bottom out in
  4994       // uncommon traps.  If the debug-info of the trap omits
  4995       // any reference to the allocation, as we've already
  4996       // observed, then there can be no objection to the trap.
  4997       bool found_trap = false;
  4998       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
  4999         Node* obs = not_ctl->fast_out(j);
  5000         if (obs->in(0) == not_ctl && obs->is_Call() &&
  5001             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
  5002           found_trap = true; break;
  5005       if (found_trap) {
  5006         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
  5007         continue;
  5010     return NULL;
  5013   // If we get this far, we have an allocation which immediately
  5014   // precedes the arraycopy, and we can take over zeroing the new object.
  5015   // The arraycopy will finish the initialization, and provide
  5016   // a new control state to which we will anchor the destination pointer.
  5018   return alloc;
  5021 // Helper for initialization of arrays, creating a ClearArray.
  5022 // It writes zero bits in [start..end), within the body of an array object.
  5023 // The memory effects are all chained onto the 'adr_type' alias category.
  5024 //
  5025 // Since the object is otherwise uninitialized, we are free
  5026 // to put a little "slop" around the edges of the cleared area,
  5027 // as long as it does not go back into the array's header,
  5028 // or beyond the array end within the heap.
  5029 //
  5030 // The lower edge can be rounded down to the nearest jint and the
  5031 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
  5032 //
  5033 // Arguments:
  5034 //   adr_type           memory slice where writes are generated
  5035 //   dest               oop of the destination array
  5036 //   basic_elem_type    element type of the destination
  5037 //   slice_idx          array index of first element to store
  5038 //   slice_len          number of elements to store (or NULL)
  5039 //   dest_size          total size in bytes of the array object
  5040 //
  5041 // Exactly one of slice_len or dest_size must be non-NULL.
  5042 // If dest_size is non-NULL, zeroing extends to the end of the object.
  5043 // If slice_len is non-NULL, the slice_idx value must be a constant.
  5044 void
  5045 LibraryCallKit::generate_clear_array(const TypePtr* adr_type,
  5046                                      Node* dest,
  5047                                      BasicType basic_elem_type,
  5048                                      Node* slice_idx,
  5049                                      Node* slice_len,
  5050                                      Node* dest_size) {
  5051   // one or the other but not both of slice_len and dest_size:
  5052   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
  5053   if (slice_len == NULL)  slice_len = top();
  5054   if (dest_size == NULL)  dest_size = top();
  5056   // operate on this memory slice:
  5057   Node* mem = memory(adr_type); // memory slice to operate on
  5059   // scaling and rounding of indexes:
  5060   int scale = exact_log2(type2aelembytes(basic_elem_type));
  5061   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  5062   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
  5063   int bump_bit  = (-1 << scale) & BytesPerInt;
  5065   // determine constant starts and ends
  5066   const intptr_t BIG_NEG = -128;
  5067   assert(BIG_NEG + 2*abase < 0, "neg enough");
  5068   intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);
  5069   intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);
  5070   if (slice_len_con == 0) {
  5071     return;                     // nothing to do here
  5073   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
  5074   intptr_t end_con   = find_intptr_t_con(dest_size, -1);
  5075   if (slice_idx_con >= 0 && slice_len_con >= 0) {
  5076     assert(end_con < 0, "not two cons");
  5077     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
  5078                        BytesPerLong);
  5081   if (start_con >= 0 && end_con >= 0) {
  5082     // Constant start and end.  Simple.
  5083     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5084                                        start_con, end_con, &_gvn);
  5085   } else if (start_con >= 0 && dest_size != top()) {
  5086     // Constant start, pre-rounded end after the tail of the array.
  5087     Node* end = dest_size;
  5088     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5089                                        start_con, end, &_gvn);
  5090   } else if (start_con >= 0 && slice_len != top()) {
  5091     // Constant start, non-constant end.  End needs rounding up.
  5092     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
  5093     intptr_t end_base  = abase + (slice_idx_con << scale);
  5094     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
  5095     Node*    end       = ConvI2X(slice_len);
  5096     if (scale != 0)
  5097       end = _gvn.transform( new(C,3) LShiftXNode(end, intcon(scale) ));
  5098     end_base += end_round;
  5099     end = _gvn.transform( new(C,3) AddXNode(end, MakeConX(end_base)) );
  5100     end = _gvn.transform( new(C,3) AndXNode(end, MakeConX(~end_round)) );
  5101     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5102                                        start_con, end, &_gvn);
  5103   } else if (start_con < 0 && dest_size != top()) {
  5104     // Non-constant start, pre-rounded end after the tail of the array.
  5105     // This is almost certainly a "round-to-end" operation.
  5106     Node* start = slice_idx;
  5107     start = ConvI2X(start);
  5108     if (scale != 0)
  5109       start = _gvn.transform( new(C,3) LShiftXNode( start, intcon(scale) ));
  5110     start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(abase)) );
  5111     if ((bump_bit | clear_low) != 0) {
  5112       int to_clear = (bump_bit | clear_low);
  5113       // Align up mod 8, then store a jint zero unconditionally
  5114       // just before the mod-8 boundary.
  5115       if (((abase + bump_bit) & ~to_clear) - bump_bit
  5116           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
  5117         bump_bit = 0;
  5118         assert((abase & to_clear) == 0, "array base must be long-aligned");
  5119       } else {
  5120         // Bump 'start' up to (or past) the next jint boundary:
  5121         start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(bump_bit)) );
  5122         assert((abase & clear_low) == 0, "array base must be int-aligned");
  5124       // Round bumped 'start' down to jlong boundary in body of array.
  5125       start = _gvn.transform( new(C,3) AndXNode(start, MakeConX(~to_clear)) );
  5126       if (bump_bit != 0) {
  5127         // Store a zero to the immediately preceding jint:
  5128         Node* x1 = _gvn.transform( new(C,3) AddXNode(start, MakeConX(-bump_bit)) );
  5129         Node* p1 = basic_plus_adr(dest, x1);
  5130         mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT);
  5131         mem = _gvn.transform(mem);
  5134     Node* end = dest_size; // pre-rounded
  5135     mem = ClearArrayNode::clear_memory(control(), mem, dest,
  5136                                        start, end, &_gvn);
  5137   } else {
  5138     // Non-constant start, unrounded non-constant end.
  5139     // (Nobody zeroes a random midsection of an array using this routine.)
  5140     ShouldNotReachHere();       // fix caller
  5143   // Done.
  5144   set_memory(mem, adr_type);
  5148 bool
  5149 LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,
  5150                                          BasicType basic_elem_type,
  5151                                          AllocateNode* alloc,
  5152                                          Node* src,  Node* src_offset,
  5153                                          Node* dest, Node* dest_offset,
  5154                                          Node* dest_size, bool dest_uninitialized) {
  5155   // See if there is an advantage from block transfer.
  5156   int scale = exact_log2(type2aelembytes(basic_elem_type));
  5157   if (scale >= LogBytesPerLong)
  5158     return false;               // it is already a block transfer
  5160   // Look at the alignment of the starting offsets.
  5161   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
  5162   const intptr_t BIG_NEG = -128;
  5163   assert(BIG_NEG + 2*abase < 0, "neg enough");
  5165   intptr_t src_off  = abase + ((intptr_t) find_int_con(src_offset, -1)  << scale);
  5166   intptr_t dest_off = abase + ((intptr_t) find_int_con(dest_offset, -1) << scale);
  5167   if (src_off < 0 || dest_off < 0)
  5168     // At present, we can only understand constants.
  5169     return false;
  5171   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
  5172     // Non-aligned; too bad.
  5173     // One more chance:  Pick off an initial 32-bit word.
  5174     // This is a common case, since abase can be odd mod 8.
  5175     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
  5176         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
  5177       Node* sptr = basic_plus_adr(src,  src_off);
  5178       Node* dptr = basic_plus_adr(dest, dest_off);
  5179       Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type);
  5180       store_to_memory(control(), dptr, sval, T_INT, adr_type);
  5181       src_off += BytesPerInt;
  5182       dest_off += BytesPerInt;
  5183     } else {
  5184       return false;
  5187   assert(src_off % BytesPerLong == 0, "");
  5188   assert(dest_off % BytesPerLong == 0, "");
  5190   // Do this copy by giant steps.
  5191   Node* sptr  = basic_plus_adr(src,  src_off);
  5192   Node* dptr  = basic_plus_adr(dest, dest_off);
  5193   Node* countx = dest_size;
  5194   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(dest_off)) );
  5195   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong)) );
  5197   bool disjoint_bases = true;   // since alloc != NULL
  5198   generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,
  5199                                sptr, NULL, dptr, NULL, countx, dest_uninitialized);
  5201   return true;
  5205 // Helper function; generates code for the slow case.
  5206 // We make a call to a runtime method which emulates the native method,
  5207 // but without the native wrapper overhead.
  5208 void
  5209 LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,
  5210                                         Node* src,  Node* src_offset,
  5211                                         Node* dest, Node* dest_offset,
  5212                                         Node* copy_length, bool dest_uninitialized) {
  5213   assert(!dest_uninitialized, "Invariant");
  5214   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,
  5215                                  OptoRuntime::slow_arraycopy_Type(),
  5216                                  OptoRuntime::slow_arraycopy_Java(),
  5217                                  "slow_arraycopy", adr_type,
  5218                                  src, src_offset, dest, dest_offset,
  5219                                  copy_length);
  5221   // Handle exceptions thrown by this fellow:
  5222   make_slow_call_ex(call, env()->Throwable_klass(), false);
  5225 // Helper function; generates code for cases requiring runtime checks.
  5226 Node*
  5227 LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,
  5228                                              Node* dest_elem_klass,
  5229                                              Node* src,  Node* src_offset,
  5230                                              Node* dest, Node* dest_offset,
  5231                                              Node* copy_length, bool dest_uninitialized) {
  5232   if (stopped())  return NULL;
  5234   address copyfunc_addr = StubRoutines::checkcast_arraycopy(dest_uninitialized);
  5235   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5236     return NULL;
  5239   // Pick out the parameters required to perform a store-check
  5240   // for the target array.  This is an optimistic check.  It will
  5241   // look in each non-null element's class, at the desired klass's
  5242   // super_check_offset, for the desired klass.
  5243   int sco_offset = Klass::super_check_offset_offset_in_bytes() + sizeof(oopDesc);
  5244   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
  5245   Node* n3 = new(C, 3) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr());
  5246   Node* check_offset = ConvI2X(_gvn.transform(n3));
  5247   Node* check_value  = dest_elem_klass;
  5249   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
  5250   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
  5252   // (We know the arrays are never conjoint, because their types differ.)
  5253   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5254                                  OptoRuntime::checkcast_arraycopy_Type(),
  5255                                  copyfunc_addr, "checkcast_arraycopy", adr_type,
  5256                                  // five arguments, of which two are
  5257                                  // intptr_t (jlong in LP64)
  5258                                  src_start, dest_start,
  5259                                  copy_length XTOP,
  5260                                  check_offset XTOP,
  5261                                  check_value);
  5263   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
  5267 // Helper function; generates code for cases requiring runtime checks.
  5268 Node*
  5269 LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,
  5270                                            Node* src,  Node* src_offset,
  5271                                            Node* dest, Node* dest_offset,
  5272                                            Node* copy_length, bool dest_uninitialized) {
  5273   assert(!dest_uninitialized, "Invariant");
  5274   if (stopped())  return NULL;
  5275   address copyfunc_addr = StubRoutines::generic_arraycopy();
  5276   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
  5277     return NULL;
  5280   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
  5281                     OptoRuntime::generic_arraycopy_Type(),
  5282                     copyfunc_addr, "generic_arraycopy", adr_type,
  5283                     src, src_offset, dest, dest_offset, copy_length);
  5285   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
  5288 // Helper function; generates the fast out-of-line call to an arraycopy stub.
  5289 void
  5290 LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,
  5291                                              BasicType basic_elem_type,
  5292                                              bool disjoint_bases,
  5293                                              Node* src,  Node* src_offset,
  5294                                              Node* dest, Node* dest_offset,
  5295                                              Node* copy_length, bool dest_uninitialized) {
  5296   if (stopped())  return;               // nothing to do
  5298   Node* src_start  = src;
  5299   Node* dest_start = dest;
  5300   if (src_offset != NULL || dest_offset != NULL) {
  5301     assert(src_offset != NULL && dest_offset != NULL, "");
  5302     src_start  = array_element_address(src,  src_offset,  basic_elem_type);
  5303     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
  5306   // Figure out which arraycopy runtime method to call.
  5307   const char* copyfunc_name = "arraycopy";
  5308   address     copyfunc_addr =
  5309       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
  5310                           disjoint_bases, copyfunc_name, dest_uninitialized);
  5312   // Call it.  Note that the count_ix value is not scaled to a byte-size.
  5313   make_runtime_call(RC_LEAF|RC_NO_FP,
  5314                     OptoRuntime::fast_arraycopy_Type(),
  5315                     copyfunc_addr, copyfunc_name, adr_type,
  5316                     src_start, dest_start, copy_length XTOP);

mercurial