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  */
  24 
  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"
  40 
  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;
  47 
  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 };
  60 
  61 
  62 // Local helper class for LibraryIntrinsic:
  63 class LibraryCallKit : public GraphKit {
  64  private:
  65   LibraryIntrinsic* _intrinsic;   // the library intrinsic being called
  66 
  67  public:
  68   LibraryCallKit(JVMState* caller, LibraryIntrinsic* intrinsic)
  69     : GraphKit(caller),
  70       _intrinsic(intrinsic)
  71   {
  72   }
  73 
  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(); }
  81 
  82   bool try_to_inline();
  83 
  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 need_pre_barrier = true);
 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   }
 148 
 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();
 177 
 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();
 191 
 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);
 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);
 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 need_pre_barrier = true);
 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);
 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 need_pre_barrier = true);
 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 };
 243 
 244 
 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");
 249 
 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   }
 256 
 257   if (!m->is_loaded()) {
 258     // do not attempt to inline unloaded methods
 259     return NULL;
 260   }
 261 
 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   }
 274 
 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   }
 287 
 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;
 321 
 322   case vmIntrinsics::_get_AtomicLong:
 323   case vmIntrinsics::_attemptUpdate:
 324     if (!InlineAtomicLong)  return NULL;
 325     break;
 326 
 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;
 332 
 333   case vmIntrinsics::_bitCount_i:
 334   case vmIntrinsics::_bitCount_l:
 335     if (!UsePopCountInstruction)  return NULL;
 336     break;
 337 
 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   }
 343 
 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   }
 351 
 352   // -XX:-InlineThreadNatives disables natives from the Thread class.
 353   if (m->holder()->name() == ciSymbol::java_lang_Thread()) {
 354     if (!InlineThreadNatives)  return NULL;
 355   }
 356 
 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   }
 363 
 364   // -XX:-InlineUnsafeOps disables natives from the Unsafe class.
 365   if (m->holder()->name() == ciSymbol::sun_misc_Unsafe()) {
 366     if (!InlineUnsafeOps)  return NULL;
 367   }
 368 
 369   return new LibraryIntrinsic(m, is_virtual, (vmIntrinsics::ID) id);
 370 }
 371 
 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 }
 377 
 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   }
 406 
 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 }
 417 
 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;
 423 
 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();
 431 
 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());
 443 
 444   case vmIntrinsics::_min:
 445   case vmIntrinsics::_max:
 446     return inline_min_max(intrinsic_id());
 447 
 448   case vmIntrinsics::_arraycopy:
 449     return inline_arraycopy();
 450 
 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();
 457 
 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);
 476 
 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);
 495 
 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);
 512 
 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);
 529 
 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);
 548 
 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);
 567 
 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);
 576 
 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);
 583 
 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);
 590 
 591   case vmIntrinsics::_currentThread:
 592     return inline_native_currentThread();
 593   case vmIntrinsics::_isInterrupted:
 594     return inline_native_isInterrupted();
 595 
 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());
 616 
 617   case vmIntrinsics::_isAssignableFrom:
 618     return inline_native_subtype_check();
 619 
 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());
 629 
 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());
 637 
 638   case vmIntrinsics::_numberOfLeadingZeros_i:
 639   case vmIntrinsics::_numberOfLeadingZeros_l:
 640     return inline_numberOfLeadingZeros(intrinsic_id());
 641 
 642   case vmIntrinsics::_numberOfTrailingZeros_i:
 643   case vmIntrinsics::_numberOfTrailingZeros_l:
 644     return inline_numberOfTrailingZeros(intrinsic_id());
 645 
 646   case vmIntrinsics::_bitCount_i:
 647   case vmIntrinsics::_bitCount_l:
 648     return inline_bitCount(intrinsic_id());
 649 
 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());
 655 
 656   case vmIntrinsics::_get_AtomicLong:
 657     return inline_native_AtomicLong_get();
 658   case vmIntrinsics::_attemptUpdate:
 659     return inline_native_AtomicLong_attemptUpdate();
 660 
 661   case vmIntrinsics::_getCallerClass:
 662     return inline_native_Reflection_getCallerClass();
 663 
 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 }
 676 
 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 }
 685 
 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   }
 701 
 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   }
 708 
 709   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 710 
 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   }
 716 
 717   if (region != NULL)
 718     region->add_req(if_slow);
 719 
 720   Node* if_fast = _gvn.transform( new (C, 1) IfFalseNode(iff) );
 721   set_control(if_fast);
 722 
 723   return if_slow;
 724 }
 725 
 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 }
 732 
 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 }
 750 
 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 }
 769 
 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 }
 801 
 802 
 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 }
 813 
 814 
 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();
 821 
 822   Node* no_ctrl = NULL;
 823 
 824   ciInstanceKlass* klass = env()->String_klass();
 825   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
 826 
 827   const TypeAryPtr* value_type =
 828         TypeAryPtr::make(TypePtr::NotNull,
 829                          TypeAry::make(TypeInt::CHAR,TypeInt::POS),
 830                          ciTypeArrayKlass::make(T_CHAR), true, 0);
 831 
 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);
 838 
 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);
 846 
 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   }
 865 
 866   // All these intrinsics have checks.
 867   C->set_has_split_ifs(true); // Has chance for split-if optimization
 868 
 869   return _gvn.transform(result);
 870 }
 871 
 872 //------------------------------inline_string_compareTo------------------------
 873 bool LibraryCallKit::inline_string_compareTo() {
 874 
 875   if (!Matcher::has_match_rule(Op_StrComp)) return false;
 876 
 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();
 880 
 881   _sp += 2;
 882   Node *argument = pop();  // pop non-receiver first:  it was pushed second
 883   Node *receiver = pop();
 884 
 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   }
 896 
 897   ciInstanceKlass* klass = env()->String_klass();
 898   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
 899   Node* no_ctrl = NULL;
 900 
 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));
 904 
 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));
 907 
 908   Node* compare = make_string_method_node(Op_StrComp, receiver, receiver_cnt, argument, argument_cnt);
 909   push(compare);
 910   return true;
 911 }
 912 
 913 //------------------------------inline_string_equals------------------------
 914 bool LibraryCallKit::inline_string_equals() {
 915 
 916   if (!Matcher::has_match_rule(Op_StrEquals)) return false;
 917 
 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();
 921 
 922   int nargs = 2;
 923   _sp += nargs;
 924   Node* argument = pop();  // pop non-receiver first:  it was pushed second
 925   Node* receiver = pop();
 926 
 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;
 936 
 937   if (stopped()) {
 938     return true;
 939   }
 940 
 941   // paths (plus control) merge
 942   RegionNode* region = new (C, 5) RegionNode(5);
 943   Node* phi = new (C, 5) PhiNode(region, TypeInt::BOOL);
 944 
 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));
 948 
 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   }
 955 
 956   // get String klass for instanceOf
 957   ciInstanceKlass* klass = env()->String_klass();
 958 
 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));
 965 
 966     Node* inst_false = generate_guard(bol, NULL, PROB_MIN);
 967     //instanceOf == true, fallthrough
 968 
 969     if (inst_false != NULL) {
 970       phi->init_req(3, intcon(0));
 971       region->init_req(3, inst_false);
 972     }
 973   }
 974 
 975   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
 976 
 977   Node* no_ctrl = NULL;
 978   Node* receiver_cnt;
 979   Node* argument_cnt;
 980 
 981   if (!stopped()) {
 982     // Properly cast the argument to String
 983     argument = _gvn.transform(new (C, 2) CheckCastPPNode(control(), argument, string_type));
 984 
 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));
 988 
 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));
 992 
 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);
1000     }
1001   }
1002 
1003   // Check for count == 0 is done by mach node StrEquals.
1004 
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());
1009   }
1010 
1011   // post merge
1012   set_control(_gvn.transform(region));
1013   record_for_igvn(region);
1014 
1015   push(_gvn.transform(phi));
1016 
1017   return true;
1018 }
1019 
1020 //------------------------------inline_array_equals----------------------------
1021 bool LibraryCallKit::inline_array_equals() {
1022 
1023   if (!Matcher::has_match_rule(Op_AryEq)) return false;
1024 
1025   _sp += 2;
1026   Node *argument2 = pop();
1027   Node *argument1 = pop();
1028 
1029   Node* equals =
1030     _gvn.transform(new (C, 4) AryEqNode(control(), memory(TypeAryPtr::CHARS),
1031                                         argument1, argument2) );
1032   push(equals);
1033   return true;
1034 }
1035 
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 // }
1095 
1096 //------------------------------string_indexOf------------------------
1097 Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_array, jint targetOffset_i,
1098                                      jint cache_i, jint md2_i) {
1099 
1100   Node* no_ctrl  = NULL;
1101   float likely   = PROB_LIKELY(0.9);
1102   float unlikely = PROB_UNLIKELY(0.9);
1103 
1104   const int value_offset  = java_lang_String::value_offset_in_bytes();
1105   const int count_offset  = java_lang_String::count_offset_in_bytes();
1106   const int offset_offset = java_lang_String::offset_offset_in_bytes();
1107 
1108   ciInstanceKlass* klass = env()->String_klass();
1109   const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1110   const TypeAryPtr*  source_type = TypeAryPtr::make(TypePtr::NotNull, TypeAry::make(TypeInt::CHAR,TypeInt::POS), ciTypeArrayKlass::make(T_CHAR), true, 0);
1111 
1112   Node* sourceOffseta = basic_plus_adr(string_object, string_object, offset_offset);
1113   Node* sourceOffset  = make_load(no_ctrl, sourceOffseta, TypeInt::INT, T_INT, string_type->add_offset(offset_offset));
1114   Node* sourceCounta  = basic_plus_adr(string_object, string_object, count_offset);
1115   Node* sourceCount   = make_load(no_ctrl, sourceCounta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
1116   Node* sourcea       = basic_plus_adr(string_object, string_object, value_offset);
1117   Node* source        = make_load(no_ctrl, sourcea, source_type, T_OBJECT, string_type->add_offset(value_offset));
1118 
1119   Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array)) );
1120   jint target_length = target_array->length();
1121   const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin));
1122   const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot);
1123 
1124   IdealKit kit(gvn(), control(), merged_memory(), false, true);
1125 #define __ kit.
1126   Node* zero             = __ ConI(0);
1127   Node* one              = __ ConI(1);
1128   Node* cache            = __ ConI(cache_i);
1129   Node* md2              = __ ConI(md2_i);
1130   Node* lastChar         = __ ConI(target_array->char_at(target_length - 1));
1131   Node* targetCount      = __ ConI(target_length);
1132   Node* targetCountLess1 = __ ConI(target_length - 1);
1133   Node* targetOffset     = __ ConI(targetOffset_i);
1134   Node* sourceEnd        = __ SubI(__ AddI(sourceOffset, sourceCount), targetCountLess1);
1135 
1136   IdealVariable rtn(kit), i(kit), j(kit); __ declarations_done();
1137   Node* outer_loop = __ make_label(2 /* goto */);
1138   Node* return_    = __ make_label(1);
1139 
1140   __ set(rtn,__ ConI(-1));
1141   __ loop(i, sourceOffset, BoolTest::lt, sourceEnd); {
1142        Node* i2  = __ AddI(__ value(i), targetCountLess1);
1143        // pin to prohibit loading of "next iteration" value which may SEGV (rare)
1144        Node* src = load_array_element(__ ctrl(), source, i2, TypeAryPtr::CHARS);
1145        __ if_then(src, BoolTest::eq, lastChar, unlikely); {
1146          __ loop(j, zero, BoolTest::lt, targetCountLess1); {
1147               Node* tpj = __ AddI(targetOffset, __ value(j));
1148               Node* targ = load_array_element(no_ctrl, target, tpj, target_type);
1149               Node* ipj  = __ AddI(__ value(i), __ value(j));
1150               Node* src2 = load_array_element(no_ctrl, source, ipj, TypeAryPtr::CHARS);
1151               __ if_then(targ, BoolTest::ne, src2); {
1152                 __ if_then(__ AndI(cache, __ LShiftI(one, src2)), BoolTest::eq, zero); {
1153                   __ if_then(md2, BoolTest::lt, __ AddI(__ value(j), one)); {
1154                     __ increment(i, __ AddI(__ value(j), one));
1155                     __ goto_(outer_loop);
1156                   } __ end_if(); __ dead(j);
1157                 }__ end_if(); __ dead(j);
1158                 __ increment(i, md2);
1159                 __ goto_(outer_loop);
1160               }__ end_if();
1161               __ increment(j, one);
1162          }__ end_loop(); __ dead(j);
1163          __ set(rtn, __ SubI(__ value(i), sourceOffset)); __ dead(i);
1164          __ goto_(return_);
1165        }__ end_if();
1166        __ if_then(__ AndI(cache, __ LShiftI(one, src)), BoolTest::eq, zero, likely); {
1167          __ increment(i, targetCountLess1);
1168        }__ end_if();
1169        __ increment(i, one);
1170        __ bind(outer_loop);
1171   }__ end_loop(); __ dead(i);
1172   __ bind(return_);
1173 
1174   // Final sync IdealKit and GraphKit.
1175   sync_kit(kit);
1176   Node* result = __ value(rtn);
1177 #undef __
1178   C->set_has_loops(true);
1179   return result;
1180 }
1181 
1182 //------------------------------inline_string_indexOf------------------------
1183 bool LibraryCallKit::inline_string_indexOf() {
1184 
1185   const int value_offset  = java_lang_String::value_offset_in_bytes();
1186   const int count_offset  = java_lang_String::count_offset_in_bytes();
1187   const int offset_offset = java_lang_String::offset_offset_in_bytes();
1188 
1189   _sp += 2;
1190   Node *argument = pop();  // pop non-receiver first:  it was pushed second
1191   Node *receiver = pop();
1192 
1193   Node* result;
1194   // Disable the use of pcmpestri until it can be guaranteed that
1195   // the load doesn't cross into the uncommited space.
1196   if (false && Matcher::has_match_rule(Op_StrIndexOf) &&
1197       UseSSE42Intrinsics) {
1198     // Generate SSE4.2 version of indexOf
1199     // We currently only have match rules that use SSE4.2
1200 
1201     // Null check on self without removing any arguments.  The argument
1202     // null check technically happens in the wrong place, which can lead to
1203     // invalid stack traces when string compare is inlined into a method
1204     // which handles NullPointerExceptions.
1205     _sp += 2;
1206     receiver = do_null_check(receiver, T_OBJECT);
1207     argument = do_null_check(argument, T_OBJECT);
1208     _sp -= 2;
1209 
1210     if (stopped()) {
1211       return true;
1212     }
1213 
1214     // Make the merge point
1215     RegionNode* result_rgn = new (C, 3) RegionNode(3);
1216     Node*       result_phi = new (C, 3) PhiNode(result_rgn, TypeInt::INT);
1217     Node* no_ctrl  = NULL;
1218 
1219     ciInstanceKlass* klass = env()->String_klass();
1220     const TypeOopPtr* string_type = TypeOopPtr::make_from_klass(klass);
1221 
1222     // Get counts for string and substr
1223     Node* source_cnta = basic_plus_adr(receiver, receiver, count_offset);
1224     Node* source_cnt  = make_load(no_ctrl, source_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
1225 
1226     Node* substr_cnta = basic_plus_adr(argument, argument, count_offset);
1227     Node* substr_cnt  = make_load(no_ctrl, substr_cnta, TypeInt::INT, T_INT, string_type->add_offset(count_offset));
1228 
1229     // Check for substr count > string count
1230     Node* cmp = _gvn.transform( new(C, 3) CmpINode(substr_cnt, source_cnt) );
1231     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::gt) );
1232     Node* if_gt = generate_slow_guard(bol, NULL);
1233     if (if_gt != NULL) {
1234       result_phi->init_req(2, intcon(-1));
1235       result_rgn->init_req(2, if_gt);
1236     }
1237 
1238     if (!stopped()) {
1239       result = make_string_method_node(Op_StrIndexOf, receiver, source_cnt, argument, substr_cnt);
1240       result_phi->init_req(1, result);
1241       result_rgn->init_req(1, control());
1242     }
1243     set_control(_gvn.transform(result_rgn));
1244     record_for_igvn(result_rgn);
1245     result = _gvn.transform(result_phi);
1246 
1247   } else { //Use LibraryCallKit::string_indexOf
1248     // don't intrinsify is argument isn't a constant string.
1249     if (!argument->is_Con()) {
1250      return false;
1251     }
1252     const TypeOopPtr* str_type = _gvn.type(argument)->isa_oopptr();
1253     if (str_type == NULL) {
1254       return false;
1255     }
1256     ciInstanceKlass* klass = env()->String_klass();
1257     ciObject* str_const = str_type->const_oop();
1258     if (str_const == NULL || str_const->klass() != klass) {
1259       return false;
1260     }
1261     ciInstance* str = str_const->as_instance();
1262     assert(str != NULL, "must be instance");
1263 
1264     ciObject* v = str->field_value_by_offset(value_offset).as_object();
1265     int       o = str->field_value_by_offset(offset_offset).as_int();
1266     int       c = str->field_value_by_offset(count_offset).as_int();
1267     ciTypeArray* pat = v->as_type_array(); // pattern (argument) character array
1268 
1269     // constant strings have no offset and count == length which
1270     // simplifies the resulting code somewhat so lets optimize for that.
1271     if (o != 0 || c != pat->length()) {
1272      return false;
1273     }
1274 
1275     // Null check on self without removing any arguments.  The argument
1276     // null check technically happens in the wrong place, which can lead to
1277     // invalid stack traces when string compare is inlined into a method
1278     // which handles NullPointerExceptions.
1279     _sp += 2;
1280     receiver = do_null_check(receiver, T_OBJECT);
1281     // No null check on the argument is needed since it's a constant String oop.
1282     _sp -= 2;
1283     if (stopped()) {
1284      return true;
1285     }
1286 
1287     // The null string as a pattern always returns 0 (match at beginning of string)
1288     if (c == 0) {
1289       push(intcon(0));
1290       return true;
1291     }
1292 
1293     // Generate default indexOf
1294     jchar lastChar = pat->char_at(o + (c - 1));
1295     int cache = 0;
1296     int i;
1297     for (i = 0; i < c - 1; i++) {
1298       assert(i < pat->length(), "out of range");
1299       cache |= (1 << (pat->char_at(o + i) & (sizeof(cache) * BitsPerByte - 1)));
1300     }
1301 
1302     int md2 = c;
1303     for (i = 0; i < c - 1; i++) {
1304       assert(i < pat->length(), "out of range");
1305       if (pat->char_at(o + i) == lastChar) {
1306         md2 = (c - 1) - i;
1307       }
1308     }
1309 
1310     result = string_indexOf(receiver, pat, o, cache, md2);
1311   }
1312 
1313   push(result);
1314   return true;
1315 }
1316 
1317 //--------------------------pop_math_arg--------------------------------
1318 // Pop a double argument to a math function from the stack
1319 // rounding it if necessary.
1320 Node * LibraryCallKit::pop_math_arg() {
1321   Node *arg = pop_pair();
1322   if( Matcher::strict_fp_requires_explicit_rounding && UseSSE<=1 )
1323     arg = _gvn.transform( new (C, 2) RoundDoubleNode(0, arg) );
1324   return arg;
1325 }
1326 
1327 //------------------------------inline_trig----------------------------------
1328 // Inline sin/cos/tan instructions, if possible.  If rounding is required, do
1329 // argument reduction which will turn into a fast/slow diamond.
1330 bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) {
1331   _sp += arg_size();            // restore stack pointer
1332   Node* arg = pop_math_arg();
1333   Node* trig = NULL;
1334 
1335   switch (id) {
1336   case vmIntrinsics::_dsin:
1337     trig = _gvn.transform((Node*)new (C, 2) SinDNode(arg));
1338     break;
1339   case vmIntrinsics::_dcos:
1340     trig = _gvn.transform((Node*)new (C, 2) CosDNode(arg));
1341     break;
1342   case vmIntrinsics::_dtan:
1343     trig = _gvn.transform((Node*)new (C, 2) TanDNode(arg));
1344     break;
1345   default:
1346     assert(false, "bad intrinsic was passed in");
1347     return false;
1348   }
1349 
1350   // Rounding required?  Check for argument reduction!
1351   if( Matcher::strict_fp_requires_explicit_rounding ) {
1352 
1353     static const double     pi_4 =  0.7853981633974483;
1354     static const double neg_pi_4 = -0.7853981633974483;
1355     // pi/2 in 80-bit extended precision
1356     // static const unsigned char pi_2_bits_x[] = {0x35,0xc2,0x68,0x21,0xa2,0xda,0x0f,0xc9,0xff,0x3f,0x00,0x00,0x00,0x00,0x00,0x00};
1357     // -pi/2 in 80-bit extended precision
1358     // 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};
1359     // Cutoff value for using this argument reduction technique
1360     //static const double    pi_2_minus_epsilon =  1.564660403643354;
1361     //static const double neg_pi_2_plus_epsilon = -1.564660403643354;
1362 
1363     // Pseudocode for sin:
1364     // if (x <= Math.PI / 4.0) {
1365     //   if (x >= -Math.PI / 4.0) return  fsin(x);
1366     //   if (x >= -Math.PI / 2.0) return -fcos(x + Math.PI / 2.0);
1367     // } else {
1368     //   if (x <=  Math.PI / 2.0) return  fcos(x - Math.PI / 2.0);
1369     // }
1370     // return StrictMath.sin(x);
1371 
1372     // Pseudocode for cos:
1373     // if (x <= Math.PI / 4.0) {
1374     //   if (x >= -Math.PI / 4.0) return  fcos(x);
1375     //   if (x >= -Math.PI / 2.0) return  fsin(x + Math.PI / 2.0);
1376     // } else {
1377     //   if (x <=  Math.PI / 2.0) return -fsin(x - Math.PI / 2.0);
1378     // }
1379     // return StrictMath.cos(x);
1380 
1381     // Actually, sticking in an 80-bit Intel value into C2 will be tough; it
1382     // requires a special machine instruction to load it.  Instead we'll try
1383     // the 'easy' case.  If we really need the extra range +/- PI/2 we'll
1384     // probably do the math inside the SIN encoding.
1385 
1386     // Make the merge point
1387     RegionNode *r = new (C, 3) RegionNode(3);
1388     Node *phi = new (C, 3) PhiNode(r,Type::DOUBLE);
1389 
1390     // Flatten arg so we need only 1 test
1391     Node *abs = _gvn.transform(new (C, 2) AbsDNode(arg));
1392     // Node for PI/4 constant
1393     Node *pi4 = makecon(TypeD::make(pi_4));
1394     // Check PI/4 : abs(arg)
1395     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(pi4,abs));
1396     // Check: If PI/4 < abs(arg) then go slow
1397     Node *bol = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::lt ) );
1398     // Branch either way
1399     IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
1400     set_control(opt_iff(r,iff));
1401 
1402     // Set fast path result
1403     phi->init_req(2,trig);
1404 
1405     // Slow path - non-blocking leaf call
1406     Node* call = NULL;
1407     switch (id) {
1408     case vmIntrinsics::_dsin:
1409       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1410                                CAST_FROM_FN_PTR(address, SharedRuntime::dsin),
1411                                "Sin", NULL, arg, top());
1412       break;
1413     case vmIntrinsics::_dcos:
1414       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1415                                CAST_FROM_FN_PTR(address, SharedRuntime::dcos),
1416                                "Cos", NULL, arg, top());
1417       break;
1418     case vmIntrinsics::_dtan:
1419       call = make_runtime_call(RC_LEAF, OptoRuntime::Math_D_D_Type(),
1420                                CAST_FROM_FN_PTR(address, SharedRuntime::dtan),
1421                                "Tan", NULL, arg, top());
1422       break;
1423     }
1424     assert(control()->in(0) == call, "");
1425     Node* slow_result = _gvn.transform(new (C, 1) ProjNode(call,TypeFunc::Parms));
1426     r->init_req(1,control());
1427     phi->init_req(1,slow_result);
1428 
1429     // Post-merge
1430     set_control(_gvn.transform(r));
1431     record_for_igvn(r);
1432     trig = _gvn.transform(phi);
1433 
1434     C->set_has_split_ifs(true); // Has chance for split-if optimization
1435   }
1436   // Push result back on JVM stack
1437   push_pair(trig);
1438   return true;
1439 }
1440 
1441 //------------------------------inline_sqrt-------------------------------------
1442 // Inline square root instruction, if possible.
1443 bool LibraryCallKit::inline_sqrt(vmIntrinsics::ID id) {
1444   assert(id == vmIntrinsics::_dsqrt, "Not square root");
1445   _sp += arg_size();        // restore stack pointer
1446   push_pair(_gvn.transform(new (C, 2) SqrtDNode(0, pop_math_arg())));
1447   return true;
1448 }
1449 
1450 //------------------------------inline_abs-------------------------------------
1451 // Inline absolute value instruction, if possible.
1452 bool LibraryCallKit::inline_abs(vmIntrinsics::ID id) {
1453   assert(id == vmIntrinsics::_dabs, "Not absolute value");
1454   _sp += arg_size();        // restore stack pointer
1455   push_pair(_gvn.transform(new (C, 2) AbsDNode(pop_math_arg())));
1456   return true;
1457 }
1458 
1459 //------------------------------inline_exp-------------------------------------
1460 // Inline exp instructions, if possible.  The Intel hardware only misses
1461 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
1462 bool LibraryCallKit::inline_exp(vmIntrinsics::ID id) {
1463   assert(id == vmIntrinsics::_dexp, "Not exp");
1464 
1465   // If this inlining ever returned NaN in the past, we do not intrinsify it
1466   // every again.  NaN results requires StrictMath.exp handling.
1467   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
1468 
1469   // Do not intrinsify on older platforms which lack cmove.
1470   if (ConditionalMoveLimit == 0)  return false;
1471 
1472   _sp += arg_size();        // restore stack pointer
1473   Node *x = pop_math_arg();
1474   Node *result = _gvn.transform(new (C, 2) ExpDNode(0,x));
1475 
1476   //-------------------
1477   //result=(result.isNaN())? StrictMath::exp():result;
1478   // Check: If isNaN() by checking result!=result? then go to Strict Math
1479   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
1480   // Build the boolean node
1481   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
1482 
1483   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1484     // End the current control-flow path
1485     push_pair(x);
1486     // Math.exp intrinsic returned a NaN, which requires StrictMath.exp
1487     // to handle.  Recompile without intrinsifying Math.exp
1488     uncommon_trap(Deoptimization::Reason_intrinsic,
1489                   Deoptimization::Action_make_not_entrant);
1490   }
1491 
1492   C->set_has_split_ifs(true); // Has chance for split-if optimization
1493 
1494   push_pair(result);
1495 
1496   return true;
1497 }
1498 
1499 //------------------------------inline_pow-------------------------------------
1500 // Inline power instructions, if possible.
1501 bool LibraryCallKit::inline_pow(vmIntrinsics::ID id) {
1502   assert(id == vmIntrinsics::_dpow, "Not pow");
1503 
1504   // If this inlining ever returned NaN in the past, we do not intrinsify it
1505   // every again.  NaN results requires StrictMath.pow handling.
1506   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
1507 
1508   // Do not intrinsify on older platforms which lack cmove.
1509   if (ConditionalMoveLimit == 0)  return false;
1510 
1511   // Pseudocode for pow
1512   // if (x <= 0.0) {
1513   //   if ((double)((int)y)==y) { // if y is int
1514   //     result = ((1&(int)y)==0)?-DPow(abs(x), y):DPow(abs(x), y)
1515   //   } else {
1516   //     result = NaN;
1517   //   }
1518   // } else {
1519   //   result = DPow(x,y);
1520   // }
1521   // if (result != result)?  {
1522   //   uncommon_trap();
1523   // }
1524   // return result;
1525 
1526   _sp += arg_size();        // restore stack pointer
1527   Node* y = pop_math_arg();
1528   Node* x = pop_math_arg();
1529 
1530   Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, x, y) );
1531 
1532   // Short form: if not top-level (i.e., Math.pow but inlining Math.pow
1533   // inside of something) then skip the fancy tests and just check for
1534   // NaN result.
1535   Node *result = NULL;
1536   if( jvms()->depth() >= 1 ) {
1537     result = fast_result;
1538   } else {
1539 
1540     // Set the merge point for If node with condition of (x <= 0.0)
1541     // There are four possible paths to region node and phi node
1542     RegionNode *r = new (C, 4) RegionNode(4);
1543     Node *phi = new (C, 4) PhiNode(r, Type::DOUBLE);
1544 
1545     // Build the first if node: if (x <= 0.0)
1546     // Node for 0 constant
1547     Node *zeronode = makecon(TypeD::ZERO);
1548     // Check x:0
1549     Node *cmp = _gvn.transform(new (C, 3) CmpDNode(x, zeronode));
1550     // Check: If (x<=0) then go complex path
1551     Node *bol1 = _gvn.transform( new (C, 2) BoolNode( cmp, BoolTest::le ) );
1552     // Branch either way
1553     IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1554     Node *opt_test = _gvn.transform(if1);
1555     //assert( opt_test->is_If(), "Expect an IfNode");
1556     IfNode *opt_if1 = (IfNode*)opt_test;
1557     // Fast path taken; set region slot 3
1558     Node *fast_taken = _gvn.transform( new (C, 1) IfFalseNode(opt_if1) );
1559     r->init_req(3,fast_taken); // Capture fast-control
1560 
1561     // Fast path not-taken, i.e. slow path
1562     Node *complex_path = _gvn.transform( new (C, 1) IfTrueNode(opt_if1) );
1563 
1564     // Set fast path result
1565     Node *fast_result = _gvn.transform( new (C, 3) PowDNode(0, y, x) );
1566     phi->init_req(3, fast_result);
1567 
1568     // Complex path
1569     // Build the second if node (if y is int)
1570     // Node for (int)y
1571     Node *inty = _gvn.transform( new (C, 2) ConvD2INode(y));
1572     // Node for (double)((int) y)
1573     Node *doubleinty= _gvn.transform( new (C, 2) ConvI2DNode(inty));
1574     // Check (double)((int) y) : y
1575     Node *cmpinty= _gvn.transform(new (C, 3) CmpDNode(doubleinty, y));
1576     // Check if (y isn't int) then go to slow path
1577 
1578     Node *bol2 = _gvn.transform( new (C, 2) BoolNode( cmpinty, BoolTest::ne ) );
1579     // Branch either way
1580     IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN);
1581     Node *slow_path = opt_iff(r,if2); // Set region path 2
1582 
1583     // Calculate DPow(abs(x), y)*(1 & (int)y)
1584     // Node for constant 1
1585     Node *conone = intcon(1);
1586     // 1& (int)y
1587     Node *signnode= _gvn.transform( new (C, 3) AndINode(conone, inty) );
1588     // zero node
1589     Node *conzero = intcon(0);
1590     // Check (1&(int)y)==0?
1591     Node *cmpeq1 = _gvn.transform(new (C, 3) CmpINode(signnode, conzero));
1592     // Check if (1&(int)y)!=0?, if so the result is negative
1593     Node *bol3 = _gvn.transform( new (C, 2) BoolNode( cmpeq1, BoolTest::ne ) );
1594     // abs(x)
1595     Node *absx=_gvn.transform( new (C, 2) AbsDNode(x));
1596     // abs(x)^y
1597     Node *absxpowy = _gvn.transform( new (C, 3) PowDNode(0, y, absx) );
1598     // -abs(x)^y
1599     Node *negabsxpowy = _gvn.transform(new (C, 2) NegDNode (absxpowy));
1600     // (1&(int)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
1601     Node *signresult = _gvn.transform( CMoveNode::make(C, NULL, bol3, absxpowy, negabsxpowy, Type::DOUBLE));
1602     // Set complex path fast result
1603     phi->init_req(2, signresult);
1604 
1605     static const jlong nan_bits = CONST64(0x7ff8000000000000);
1606     Node *slow_result = makecon(TypeD::make(*(double*)&nan_bits)); // return NaN
1607     r->init_req(1,slow_path);
1608     phi->init_req(1,slow_result);
1609 
1610     // Post merge
1611     set_control(_gvn.transform(r));
1612     record_for_igvn(r);
1613     result=_gvn.transform(phi);
1614   }
1615 
1616   //-------------------
1617   //result=(result.isNaN())? uncommon_trap():result;
1618   // Check: If isNaN() by checking result!=result? then go to Strict Math
1619   Node* cmpisnan = _gvn.transform(new (C, 3) CmpDNode(result,result));
1620   // Build the boolean node
1621   Node* bolisnum = _gvn.transform( new (C, 2) BoolNode(cmpisnan, BoolTest::eq) );
1622 
1623   { BuildCutout unless(this, bolisnum, PROB_STATIC_FREQUENT);
1624     // End the current control-flow path
1625     push_pair(x);
1626     push_pair(y);
1627     // Math.pow intrinsic returned a NaN, which requires StrictMath.pow
1628     // to handle.  Recompile without intrinsifying Math.pow.
1629     uncommon_trap(Deoptimization::Reason_intrinsic,
1630                   Deoptimization::Action_make_not_entrant);
1631   }
1632 
1633   C->set_has_split_ifs(true); // Has chance for split-if optimization
1634 
1635   push_pair(result);
1636 
1637   return true;
1638 }
1639 
1640 //------------------------------inline_trans-------------------------------------
1641 // Inline transcendental instructions, if possible.  The Intel hardware gets
1642 // these right, no funny corner cases missed.
1643 bool LibraryCallKit::inline_trans(vmIntrinsics::ID id) {
1644   _sp += arg_size();        // restore stack pointer
1645   Node* arg = pop_math_arg();
1646   Node* trans = NULL;
1647 
1648   switch (id) {
1649   case vmIntrinsics::_dlog:
1650     trans = _gvn.transform((Node*)new (C, 2) LogDNode(arg));
1651     break;
1652   case vmIntrinsics::_dlog10:
1653     trans = _gvn.transform((Node*)new (C, 2) Log10DNode(arg));
1654     break;
1655   default:
1656     assert(false, "bad intrinsic was passed in");
1657     return false;
1658   }
1659 
1660   // Push result back on JVM stack
1661   push_pair(trans);
1662   return true;
1663 }
1664 
1665 //------------------------------runtime_math-----------------------------
1666 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1667   Node* a = NULL;
1668   Node* b = NULL;
1669 
1670   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1671          "must be (DD)D or (D)D type");
1672 
1673   // Inputs
1674   _sp += arg_size();        // restore stack pointer
1675   if (call_type == OptoRuntime::Math_DD_D_Type()) {
1676     b = pop_math_arg();
1677   }
1678   a = pop_math_arg();
1679 
1680   const TypePtr* no_memory_effects = NULL;
1681   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1682                                  no_memory_effects,
1683                                  a, top(), b, b ? top() : NULL);
1684   Node* value = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+0));
1685 #ifdef ASSERT
1686   Node* value_top = _gvn.transform(new (C, 1) ProjNode(trig, TypeFunc::Parms+1));
1687   assert(value_top == top(), "second value must be top");
1688 #endif
1689 
1690   push_pair(value);
1691   return true;
1692 }
1693 
1694 //------------------------------inline_math_native-----------------------------
1695 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1696   switch (id) {
1697     // These intrinsics are not properly supported on all hardware
1698   case vmIntrinsics::_dcos: return Matcher::has_match_rule(Op_CosD) ? inline_trig(id) :
1699     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1700   case vmIntrinsics::_dsin: return Matcher::has_match_rule(Op_SinD) ? inline_trig(id) :
1701     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1702   case vmIntrinsics::_dtan: return Matcher::has_match_rule(Op_TanD) ? inline_trig(id) :
1703     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1704 
1705   case vmIntrinsics::_dlog:   return Matcher::has_match_rule(Op_LogD) ? inline_trans(id) :
1706     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1707   case vmIntrinsics::_dlog10: return Matcher::has_match_rule(Op_Log10D) ? inline_trans(id) :
1708     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1709 
1710     // These intrinsics are supported on all hardware
1711   case vmIntrinsics::_dsqrt: return Matcher::has_match_rule(Op_SqrtD) ? inline_sqrt(id) : false;
1712   case vmIntrinsics::_dabs:  return Matcher::has_match_rule(Op_AbsD)  ? inline_abs(id)  : false;
1713 
1714     // These intrinsics don't work on X86.  The ad implementation doesn't
1715     // handle NaN's properly.  Instead of returning infinity, the ad
1716     // implementation returns a NaN on overflow. See bug: 6304089
1717     // Once the ad implementations are fixed, change the code below
1718     // to match the intrinsics above
1719 
1720   case vmIntrinsics::_dexp:  return
1721     runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1722   case vmIntrinsics::_dpow:  return
1723     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
1724 
1725    // These intrinsics are not yet correctly implemented
1726   case vmIntrinsics::_datan2:
1727     return false;
1728 
1729   default:
1730     ShouldNotReachHere();
1731     return false;
1732   }
1733 }
1734 
1735 static bool is_simple_name(Node* n) {
1736   return (n->req() == 1         // constant
1737           || (n->is_Type() && n->as_Type()->type()->singleton())
1738           || n->is_Proj()       // parameter or return value
1739           || n->is_Phi()        // local of some sort
1740           );
1741 }
1742 
1743 //----------------------------inline_min_max-----------------------------------
1744 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1745   push(generate_min_max(id, argument(0), argument(1)));
1746 
1747   return true;
1748 }
1749 
1750 Node*
1751 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1752   // These are the candidate return value:
1753   Node* xvalue = x0;
1754   Node* yvalue = y0;
1755 
1756   if (xvalue == yvalue) {
1757     return xvalue;
1758   }
1759 
1760   bool want_max = (id == vmIntrinsics::_max);
1761 
1762   const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1763   const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1764   if (txvalue == NULL || tyvalue == NULL)  return top();
1765   // This is not really necessary, but it is consistent with a
1766   // hypothetical MaxINode::Value method:
1767   int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1768 
1769   // %%% This folding logic should (ideally) be in a different place.
1770   // Some should be inside IfNode, and there to be a more reliable
1771   // transformation of ?: style patterns into cmoves.  We also want
1772   // more powerful optimizations around cmove and min/max.
1773 
1774   // Try to find a dominating comparison of these guys.
1775   // It can simplify the index computation for Arrays.copyOf
1776   // and similar uses of System.arraycopy.
1777   // First, compute the normalized version of CmpI(x, y).
1778   int   cmp_op = Op_CmpI;
1779   Node* xkey = xvalue;
1780   Node* ykey = yvalue;
1781   Node* ideal_cmpxy = _gvn.transform( new(C, 3) CmpINode(xkey, ykey) );
1782   if (ideal_cmpxy->is_Cmp()) {
1783     // E.g., if we have CmpI(length - offset, count),
1784     // it might idealize to CmpI(length, count + offset)
1785     cmp_op = ideal_cmpxy->Opcode();
1786     xkey = ideal_cmpxy->in(1);
1787     ykey = ideal_cmpxy->in(2);
1788   }
1789 
1790   // Start by locating any relevant comparisons.
1791   Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
1792   Node* cmpxy = NULL;
1793   Node* cmpyx = NULL;
1794   for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
1795     Node* cmp = start_from->fast_out(k);
1796     if (cmp->outcnt() > 0 &&            // must have prior uses
1797         cmp->in(0) == NULL &&           // must be context-independent
1798         cmp->Opcode() == cmp_op) {      // right kind of compare
1799       if (cmp->in(1) == xkey && cmp->in(2) == ykey)  cmpxy = cmp;
1800       if (cmp->in(1) == ykey && cmp->in(2) == xkey)  cmpyx = cmp;
1801     }
1802   }
1803 
1804   const int NCMPS = 2;
1805   Node* cmps[NCMPS] = { cmpxy, cmpyx };
1806   int cmpn;
1807   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1808     if (cmps[cmpn] != NULL)  break;     // find a result
1809   }
1810   if (cmpn < NCMPS) {
1811     // Look for a dominating test that tells us the min and max.
1812     int depth = 0;                // Limit search depth for speed
1813     Node* dom = control();
1814     for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
1815       if (++depth >= 100)  break;
1816       Node* ifproj = dom;
1817       if (!ifproj->is_Proj())  continue;
1818       Node* iff = ifproj->in(0);
1819       if (!iff->is_If())  continue;
1820       Node* bol = iff->in(1);
1821       if (!bol->is_Bool())  continue;
1822       Node* cmp = bol->in(1);
1823       if (cmp == NULL)  continue;
1824       for (cmpn = 0; cmpn < NCMPS; cmpn++)
1825         if (cmps[cmpn] == cmp)  break;
1826       if (cmpn == NCMPS)  continue;
1827       BoolTest::mask btest = bol->as_Bool()->_test._test;
1828       if (ifproj->is_IfFalse())  btest = BoolTest(btest).negate();
1829       if (cmp->in(1) == ykey)    btest = BoolTest(btest).commute();
1830       // At this point, we know that 'x btest y' is true.
1831       switch (btest) {
1832       case BoolTest::eq:
1833         // They are proven equal, so we can collapse the min/max.
1834         // Either value is the answer.  Choose the simpler.
1835         if (is_simple_name(yvalue) && !is_simple_name(xvalue))
1836           return yvalue;
1837         return xvalue;
1838       case BoolTest::lt:          // x < y
1839       case BoolTest::le:          // x <= y
1840         return (want_max ? yvalue : xvalue);
1841       case BoolTest::gt:          // x > y
1842       case BoolTest::ge:          // x >= y
1843         return (want_max ? xvalue : yvalue);
1844       }
1845     }
1846   }
1847 
1848   // We failed to find a dominating test.
1849   // Let's pick a test that might GVN with prior tests.
1850   Node*          best_bol   = NULL;
1851   BoolTest::mask best_btest = BoolTest::illegal;
1852   for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1853     Node* cmp = cmps[cmpn];
1854     if (cmp == NULL)  continue;
1855     for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
1856       Node* bol = cmp->fast_out(j);
1857       if (!bol->is_Bool())  continue;
1858       BoolTest::mask btest = bol->as_Bool()->_test._test;
1859       if (btest == BoolTest::eq || btest == BoolTest::ne)  continue;
1860       if (cmp->in(1) == ykey)   btest = BoolTest(btest).commute();
1861       if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
1862         best_bol   = bol->as_Bool();
1863         best_btest = btest;
1864       }
1865     }
1866   }
1867 
1868   Node* answer_if_true  = NULL;
1869   Node* answer_if_false = NULL;
1870   switch (best_btest) {
1871   default:
1872     if (cmpxy == NULL)
1873       cmpxy = ideal_cmpxy;
1874     best_bol = _gvn.transform( new(C, 2) BoolNode(cmpxy, BoolTest::lt) );
1875     // and fall through:
1876   case BoolTest::lt:          // x < y
1877   case BoolTest::le:          // x <= y
1878     answer_if_true  = (want_max ? yvalue : xvalue);
1879     answer_if_false = (want_max ? xvalue : yvalue);
1880     break;
1881   case BoolTest::gt:          // x > y
1882   case BoolTest::ge:          // x >= y
1883     answer_if_true  = (want_max ? xvalue : yvalue);
1884     answer_if_false = (want_max ? yvalue : xvalue);
1885     break;
1886   }
1887 
1888   jint hi, lo;
1889   if (want_max) {
1890     // We can sharpen the minimum.
1891     hi = MAX2(txvalue->_hi, tyvalue->_hi);
1892     lo = MAX2(txvalue->_lo, tyvalue->_lo);
1893   } else {
1894     // We can sharpen the maximum.
1895     hi = MIN2(txvalue->_hi, tyvalue->_hi);
1896     lo = MIN2(txvalue->_lo, tyvalue->_lo);
1897   }
1898 
1899   // Use a flow-free graph structure, to avoid creating excess control edges
1900   // which could hinder other optimizations.
1901   // Since Math.min/max is often used with arraycopy, we want
1902   // tightly_coupled_allocation to be able to see beyond min/max expressions.
1903   Node* cmov = CMoveNode::make(C, NULL, best_bol,
1904                                answer_if_false, answer_if_true,
1905                                TypeInt::make(lo, hi, widen));
1906 
1907   return _gvn.transform(cmov);
1908 
1909   /*
1910   // This is not as desirable as it may seem, since Min and Max
1911   // nodes do not have a full set of optimizations.
1912   // And they would interfere, anyway, with 'if' optimizations
1913   // and with CMoveI canonical forms.
1914   switch (id) {
1915   case vmIntrinsics::_min:
1916     result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
1917   case vmIntrinsics::_max:
1918     result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
1919   default:
1920     ShouldNotReachHere();
1921   }
1922   */
1923 }
1924 
1925 inline int
1926 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) {
1927   const TypePtr* base_type = TypePtr::NULL_PTR;
1928   if (base != NULL)  base_type = _gvn.type(base)->isa_ptr();
1929   if (base_type == NULL) {
1930     // Unknown type.
1931     return Type::AnyPtr;
1932   } else if (base_type == TypePtr::NULL_PTR) {
1933     // Since this is a NULL+long form, we have to switch to a rawptr.
1934     base   = _gvn.transform( new (C, 2) CastX2PNode(offset) );
1935     offset = MakeConX(0);
1936     return Type::RawPtr;
1937   } else if (base_type->base() == Type::RawPtr) {
1938     return Type::RawPtr;
1939   } else if (base_type->isa_oopptr()) {
1940     // Base is never null => always a heap address.
1941     if (base_type->ptr() == TypePtr::NotNull) {
1942       return Type::OopPtr;
1943     }
1944     // Offset is small => always a heap address.
1945     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
1946     if (offset_type != NULL &&
1947         base_type->offset() == 0 &&     // (should always be?)
1948         offset_type->_lo >= 0 &&
1949         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
1950       return Type::OopPtr;
1951     }
1952     // Otherwise, it might either be oop+off or NULL+addr.
1953     return Type::AnyPtr;
1954   } else {
1955     // No information:
1956     return Type::AnyPtr;
1957   }
1958 }
1959 
1960 inline Node* LibraryCallKit::make_unsafe_address(Node* base, Node* offset) {
1961   int kind = classify_unsafe_addr(base, offset);
1962   if (kind == Type::RawPtr) {
1963     return basic_plus_adr(top(), base, offset);
1964   } else {
1965     return basic_plus_adr(base, offset);
1966   }
1967 }
1968 
1969 //-------------------inline_numberOfLeadingZeros_int/long-----------------------
1970 // inline int Integer.numberOfLeadingZeros(int)
1971 // inline int Long.numberOfLeadingZeros(long)
1972 bool LibraryCallKit::inline_numberOfLeadingZeros(vmIntrinsics::ID id) {
1973   assert(id == vmIntrinsics::_numberOfLeadingZeros_i || id == vmIntrinsics::_numberOfLeadingZeros_l, "not numberOfLeadingZeros");
1974   if (id == vmIntrinsics::_numberOfLeadingZeros_i && !Matcher::match_rule_supported(Op_CountLeadingZerosI)) return false;
1975   if (id == vmIntrinsics::_numberOfLeadingZeros_l && !Matcher::match_rule_supported(Op_CountLeadingZerosL)) return false;
1976   _sp += arg_size();  // restore stack pointer
1977   switch (id) {
1978   case vmIntrinsics::_numberOfLeadingZeros_i:
1979     push(_gvn.transform(new (C, 2) CountLeadingZerosINode(pop())));
1980     break;
1981   case vmIntrinsics::_numberOfLeadingZeros_l:
1982     push(_gvn.transform(new (C, 2) CountLeadingZerosLNode(pop_pair())));
1983     break;
1984   default:
1985     ShouldNotReachHere();
1986   }
1987   return true;
1988 }
1989 
1990 //-------------------inline_numberOfTrailingZeros_int/long----------------------
1991 // inline int Integer.numberOfTrailingZeros(int)
1992 // inline int Long.numberOfTrailingZeros(long)
1993 bool LibraryCallKit::inline_numberOfTrailingZeros(vmIntrinsics::ID id) {
1994   assert(id == vmIntrinsics::_numberOfTrailingZeros_i || id == vmIntrinsics::_numberOfTrailingZeros_l, "not numberOfTrailingZeros");
1995   if (id == vmIntrinsics::_numberOfTrailingZeros_i && !Matcher::match_rule_supported(Op_CountTrailingZerosI)) return false;
1996   if (id == vmIntrinsics::_numberOfTrailingZeros_l && !Matcher::match_rule_supported(Op_CountTrailingZerosL)) return false;
1997   _sp += arg_size();  // restore stack pointer
1998   switch (id) {
1999   case vmIntrinsics::_numberOfTrailingZeros_i:
2000     push(_gvn.transform(new (C, 2) CountTrailingZerosINode(pop())));
2001     break;
2002   case vmIntrinsics::_numberOfTrailingZeros_l:
2003     push(_gvn.transform(new (C, 2) CountTrailingZerosLNode(pop_pair())));
2004     break;
2005   default:
2006     ShouldNotReachHere();
2007   }
2008   return true;
2009 }
2010 
2011 //----------------------------inline_bitCount_int/long-----------------------
2012 // inline int Integer.bitCount(int)
2013 // inline int Long.bitCount(long)
2014 bool LibraryCallKit::inline_bitCount(vmIntrinsics::ID id) {
2015   assert(id == vmIntrinsics::_bitCount_i || id == vmIntrinsics::_bitCount_l, "not bitCount");
2016   if (id == vmIntrinsics::_bitCount_i && !Matcher::has_match_rule(Op_PopCountI)) return false;
2017   if (id == vmIntrinsics::_bitCount_l && !Matcher::has_match_rule(Op_PopCountL)) return false;
2018   _sp += arg_size();  // restore stack pointer
2019   switch (id) {
2020   case vmIntrinsics::_bitCount_i:
2021     push(_gvn.transform(new (C, 2) PopCountINode(pop())));
2022     break;
2023   case vmIntrinsics::_bitCount_l:
2024     push(_gvn.transform(new (C, 2) PopCountLNode(pop_pair())));
2025     break;
2026   default:
2027     ShouldNotReachHere();
2028   }
2029   return true;
2030 }
2031 
2032 //----------------------------inline_reverseBytes_int/long/char/short-------------------
2033 // inline Integer.reverseBytes(int)
2034 // inline Long.reverseBytes(long)
2035 // inline Character.reverseBytes(char)
2036 // inline Short.reverseBytes(short)
2037 bool LibraryCallKit::inline_reverseBytes(vmIntrinsics::ID id) {
2038   assert(id == vmIntrinsics::_reverseBytes_i || id == vmIntrinsics::_reverseBytes_l ||
2039          id == vmIntrinsics::_reverseBytes_c || id == vmIntrinsics::_reverseBytes_s,
2040          "not reverse Bytes");
2041   if (id == vmIntrinsics::_reverseBytes_i && !Matcher::has_match_rule(Op_ReverseBytesI))  return false;
2042   if (id == vmIntrinsics::_reverseBytes_l && !Matcher::has_match_rule(Op_ReverseBytesL))  return false;
2043   if (id == vmIntrinsics::_reverseBytes_c && !Matcher::has_match_rule(Op_ReverseBytesUS)) return false;
2044   if (id == vmIntrinsics::_reverseBytes_s && !Matcher::has_match_rule(Op_ReverseBytesS))  return false;
2045   _sp += arg_size();        // restore stack pointer
2046   switch (id) {
2047   case vmIntrinsics::_reverseBytes_i:
2048     push(_gvn.transform(new (C, 2) ReverseBytesINode(0, pop())));
2049     break;
2050   case vmIntrinsics::_reverseBytes_l:
2051     push_pair(_gvn.transform(new (C, 2) ReverseBytesLNode(0, pop_pair())));
2052     break;
2053   case vmIntrinsics::_reverseBytes_c:
2054     push(_gvn.transform(new (C, 2) ReverseBytesUSNode(0, pop())));
2055     break;
2056   case vmIntrinsics::_reverseBytes_s:
2057     push(_gvn.transform(new (C, 2) ReverseBytesSNode(0, pop())));
2058     break;
2059   default:
2060     ;
2061   }
2062   return true;
2063 }
2064 
2065 //----------------------------inline_unsafe_access----------------------------
2066 
2067 const static BasicType T_ADDRESS_HOLDER = T_LONG;
2068 
2069 // Interpret Unsafe.fieldOffset cookies correctly:
2070 extern jlong Unsafe_field_offset_to_byte_offset(jlong field_offset);
2071 
2072 bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, BasicType type, bool is_volatile) {
2073   if (callee()->is_static())  return false;  // caller must have the capability!
2074 
2075 #ifndef PRODUCT
2076   {
2077     ResourceMark rm;
2078     // Check the signatures.
2079     ciSignature* sig = signature();
2080 #ifdef ASSERT
2081     if (!is_store) {
2082       // Object getObject(Object base, int/long offset), etc.
2083       BasicType rtype = sig->return_type()->basic_type();
2084       if (rtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::getAddress_name())
2085           rtype = T_ADDRESS;  // it is really a C void*
2086       assert(rtype == type, "getter must return the expected value");
2087       if (!is_native_ptr) {
2088         assert(sig->count() == 2, "oop getter has 2 arguments");
2089         assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2090         assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2091       } else {
2092         assert(sig->count() == 1, "native getter has 1 argument");
2093         assert(sig->type_at(0)->basic_type() == T_LONG, "getter base is long");
2094       }
2095     } else {
2096       // void putObject(Object base, int/long offset, Object x), etc.
2097       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2098       if (!is_native_ptr) {
2099         assert(sig->count() == 3, "oop putter has 3 arguments");
2100         assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2101         assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2102       } else {
2103         assert(sig->count() == 2, "native putter has 2 arguments");
2104         assert(sig->type_at(0)->basic_type() == T_LONG, "putter base is long");
2105       }
2106       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2107       if (vtype == T_ADDRESS_HOLDER && callee()->name() == ciSymbol::putAddress_name())
2108         vtype = T_ADDRESS;  // it is really a C void*
2109       assert(vtype == type, "putter must accept the expected value");
2110     }
2111 #endif // ASSERT
2112  }
2113 #endif //PRODUCT
2114 
2115   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2116 
2117   int type_words = type2size[ (type == T_ADDRESS) ? T_LONG : type ];
2118 
2119   // Argument words:  "this" plus (oop/offset) or (lo/hi) args plus maybe 1 or 2 value words
2120   int nargs = 1 + (is_native_ptr ? 2 : 3) + (is_store ? type_words : 0);
2121 
2122   debug_only(int saved_sp = _sp);
2123   _sp += nargs;
2124 
2125   Node* val;
2126   debug_only(val = (Node*)(uintptr_t)-1);
2127 
2128 
2129   if (is_store) {
2130     // Get the value being stored.  (Pop it first; it was pushed last.)
2131     switch (type) {
2132     case T_DOUBLE:
2133     case T_LONG:
2134     case T_ADDRESS:
2135       val = pop_pair();
2136       break;
2137     default:
2138       val = pop();
2139     }
2140   }
2141 
2142   // Build address expression.  See the code in inline_unsafe_prefetch.
2143   Node *adr;
2144   Node *heap_base_oop = top();
2145   if (!is_native_ptr) {
2146     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2147     Node* offset = pop_pair();
2148     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2149     Node* base   = pop();
2150     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2151     // to be plain byte offsets, which are also the same as those accepted
2152     // by oopDesc::field_base.
2153     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2154            "fieldOffset must be byte-scaled");
2155     // 32-bit machines ignore the high half!
2156     offset = ConvL2X(offset);
2157     adr = make_unsafe_address(base, offset);
2158     heap_base_oop = base;
2159   } else {
2160     Node* ptr = pop_pair();
2161     // Adjust Java long to machine word:
2162     ptr = ConvL2X(ptr);
2163     adr = make_unsafe_address(NULL, ptr);
2164   }
2165 
2166   // Pop receiver last:  it was pushed first.
2167   Node *receiver = pop();
2168 
2169   assert(saved_sp == _sp, "must have correct argument count");
2170 
2171   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2172 
2173   // First guess at the value type.
2174   const Type *value_type = Type::get_const_basic_type(type);
2175 
2176   // Try to categorize the address.  If it comes up as TypeJavaPtr::BOTTOM,
2177   // there was not enough information to nail it down.
2178   Compile::AliasType* alias_type = C->alias_type(adr_type);
2179   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2180 
2181   // We will need memory barriers unless we can determine a unique
2182   // alias category for this reference.  (Note:  If for some reason
2183   // the barriers get omitted and the unsafe reference begins to "pollute"
2184   // the alias analysis of the rest of the graph, either Compile::can_alias
2185   // or Compile::must_alias will throw a diagnostic assert.)
2186   bool need_mem_bar = (alias_type->adr_type() == TypeOopPtr::BOTTOM);
2187 
2188   if (!is_store && type == T_OBJECT) {
2189     // Attempt to infer a sharper value type from the offset and base type.
2190     ciKlass* sharpened_klass = NULL;
2191 
2192     // See if it is an instance field, with an object type.
2193     if (alias_type->field() != NULL) {
2194       assert(!is_native_ptr, "native pointer op cannot use a java address");
2195       if (alias_type->field()->type()->is_klass()) {
2196         sharpened_klass = alias_type->field()->type()->as_klass();
2197       }
2198     }
2199 
2200     // See if it is a narrow oop array.
2201     if (adr_type->isa_aryptr()) {
2202       if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2203         const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2204         if (elem_type != NULL) {
2205           sharpened_klass = elem_type->klass();
2206         }
2207       }
2208     }
2209 
2210     if (sharpened_klass != NULL) {
2211       const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2212 
2213       // Sharpen the value type.
2214       value_type = tjp;
2215 
2216 #ifndef PRODUCT
2217       if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
2218         tty->print("  from base type:  ");   adr_type->dump();
2219         tty->print("  sharpened value: "); value_type->dump();
2220       }
2221 #endif
2222     }
2223   }
2224 
2225   // Null check on self without removing any arguments.  The argument
2226   // null check technically happens in the wrong place, which can lead to
2227   // invalid stack traces when the primitive is inlined into a method
2228   // which handles NullPointerExceptions.
2229   _sp += nargs;
2230   do_null_check(receiver, T_OBJECT);
2231   _sp -= nargs;
2232   if (stopped()) {
2233     return true;
2234   }
2235   // Heap pointers get a null-check from the interpreter,
2236   // as a courtesy.  However, this is not guaranteed by Unsafe,
2237   // and it is not possible to fully distinguish unintended nulls
2238   // from intended ones in this API.
2239 
2240   if (is_volatile) {
2241     // We need to emit leading and trailing CPU membars (see below) in
2242     // addition to memory membars when is_volatile. This is a little
2243     // too strong, but avoids the need to insert per-alias-type
2244     // volatile membars (for stores; compare Parse::do_put_xxx), which
2245     // we cannot do effectively here because we probably only have a
2246     // rough approximation of type.
2247     need_mem_bar = true;
2248     // For Stores, place a memory ordering barrier now.
2249     if (is_store)
2250       insert_mem_bar(Op_MemBarRelease);
2251   }
2252 
2253   // Memory barrier to prevent normal and 'unsafe' accesses from
2254   // bypassing each other.  Happens after null checks, so the
2255   // exception paths do not take memory state from the memory barrier,
2256   // so there's no problems making a strong assert about mixing users
2257   // of safe & unsafe memory.  Otherwise fails in a CTW of rt.jar
2258   // around 5701, class sun/reflect/UnsafeBooleanFieldAccessorImpl.
2259   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2260 
2261   if (!is_store) {
2262     Node* p = make_load(control(), adr, value_type, type, adr_type, is_volatile);
2263     // load value and push onto stack
2264     switch (type) {
2265     case T_BOOLEAN:
2266     case T_CHAR:
2267     case T_BYTE:
2268     case T_SHORT:
2269     case T_INT:
2270     case T_FLOAT:
2271     case T_OBJECT:
2272       push( p );
2273       break;
2274     case T_ADDRESS:
2275       // Cast to an int type.
2276       p = _gvn.transform( new (C, 2) CastP2XNode(NULL,p) );
2277       p = ConvX2L(p);
2278       push_pair(p);
2279       break;
2280     case T_DOUBLE:
2281     case T_LONG:
2282       push_pair( p );
2283       break;
2284     default: ShouldNotReachHere();
2285     }
2286   } else {
2287     // place effect of store into memory
2288     switch (type) {
2289     case T_DOUBLE:
2290       val = dstore_rounding(val);
2291       break;
2292     case T_ADDRESS:
2293       // Repackage the long as a pointer.
2294       val = ConvL2X(val);
2295       val = _gvn.transform( new (C, 2) CastX2PNode(val) );
2296       break;
2297     }
2298 
2299     if (type != T_OBJECT ) {
2300       (void) store_to_memory(control(), adr, val, type, adr_type, is_volatile);
2301     } else {
2302       // Possibly an oop being stored to Java heap or native memory
2303       if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(heap_base_oop))) {
2304         // oop to Java heap.
2305         (void) store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2306       } else {
2307         // We can't tell at compile time if we are storing in the Java heap or outside
2308         // of it. So we need to emit code to conditionally do the proper type of
2309         // store.
2310 
2311         IdealKit ideal(gvn(), control(),  merged_memory());
2312 #define __ ideal.
2313         // QQQ who knows what probability is here??
2314         __ if_then(heap_base_oop, BoolTest::ne, null(), PROB_UNLIKELY(0.999)); {
2315           // Sync IdealKit and graphKit.
2316           set_all_memory( __ merged_memory());
2317           set_control(__ ctrl());
2318           Node* st = store_oop_to_unknown(control(), heap_base_oop, adr, adr_type, val, type);
2319           // Update IdealKit memory.
2320           __ set_all_memory(merged_memory());
2321           __ set_ctrl(control());
2322         } __ else_(); {
2323           __ store(__ ctrl(), adr, val, type, alias_type->index(), is_volatile);
2324         } __ end_if();
2325         // Final sync IdealKit and GraphKit.
2326         sync_kit(ideal);
2327 #undef __
2328       }
2329     }
2330   }
2331 
2332   if (is_volatile) {
2333     if (!is_store)
2334       insert_mem_bar(Op_MemBarAcquire);
2335     else
2336       insert_mem_bar(Op_MemBarVolatile);
2337   }
2338 
2339   if (need_mem_bar) insert_mem_bar(Op_MemBarCPUOrder);
2340 
2341   return true;
2342 }
2343 
2344 //----------------------------inline_unsafe_prefetch----------------------------
2345 
2346 bool LibraryCallKit::inline_unsafe_prefetch(bool is_native_ptr, bool is_store, bool is_static) {
2347 #ifndef PRODUCT
2348   {
2349     ResourceMark rm;
2350     // Check the signatures.
2351     ciSignature* sig = signature();
2352 #ifdef ASSERT
2353     // Object getObject(Object base, int/long offset), etc.
2354     BasicType rtype = sig->return_type()->basic_type();
2355     if (!is_native_ptr) {
2356       assert(sig->count() == 2, "oop prefetch has 2 arguments");
2357       assert(sig->type_at(0)->basic_type() == T_OBJECT, "prefetch base is object");
2358       assert(sig->type_at(1)->basic_type() == T_LONG, "prefetcha offset is correct");
2359     } else {
2360       assert(sig->count() == 1, "native prefetch has 1 argument");
2361       assert(sig->type_at(0)->basic_type() == T_LONG, "prefetch base is long");
2362     }
2363 #endif // ASSERT
2364   }
2365 #endif // !PRODUCT
2366 
2367   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2368 
2369   // Argument words:  "this" if not static, plus (oop/offset) or (lo/hi) args
2370   int nargs = (is_static ? 0 : 1) + (is_native_ptr ? 2 : 3);
2371 
2372   debug_only(int saved_sp = _sp);
2373   _sp += nargs;
2374 
2375   // Build address expression.  See the code in inline_unsafe_access.
2376   Node *adr;
2377   if (!is_native_ptr) {
2378     // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2379     Node* offset = pop_pair();
2380     // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2381     Node* base   = pop();
2382     // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2383     // to be plain byte offsets, which are also the same as those accepted
2384     // by oopDesc::field_base.
2385     assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2386            "fieldOffset must be byte-scaled");
2387     // 32-bit machines ignore the high half!
2388     offset = ConvL2X(offset);
2389     adr = make_unsafe_address(base, offset);
2390   } else {
2391     Node* ptr = pop_pair();
2392     // Adjust Java long to machine word:
2393     ptr = ConvL2X(ptr);
2394     adr = make_unsafe_address(NULL, ptr);
2395   }
2396 
2397   if (is_static) {
2398     assert(saved_sp == _sp, "must have correct argument count");
2399   } else {
2400     // Pop receiver last:  it was pushed first.
2401     Node *receiver = pop();
2402     assert(saved_sp == _sp, "must have correct argument count");
2403 
2404     // Null check on self without removing any arguments.  The argument
2405     // null check technically happens in the wrong place, which can lead to
2406     // invalid stack traces when the primitive is inlined into a method
2407     // which handles NullPointerExceptions.
2408     _sp += nargs;
2409     do_null_check(receiver, T_OBJECT);
2410     _sp -= nargs;
2411     if (stopped()) {
2412       return true;
2413     }
2414   }
2415 
2416   // Generate the read or write prefetch
2417   Node *prefetch;
2418   if (is_store) {
2419     prefetch = new (C, 3) PrefetchWriteNode(i_o(), adr);
2420   } else {
2421     prefetch = new (C, 3) PrefetchReadNode(i_o(), adr);
2422   }
2423   prefetch->init_req(0, control());
2424   set_i_o(_gvn.transform(prefetch));
2425 
2426   return true;
2427 }
2428 
2429 //----------------------------inline_unsafe_CAS----------------------------
2430 
2431 bool LibraryCallKit::inline_unsafe_CAS(BasicType type) {
2432   // This basic scheme here is the same as inline_unsafe_access, but
2433   // differs in enough details that combining them would make the code
2434   // overly confusing.  (This is a true fact! I originally combined
2435   // them, but even I was confused by it!) As much code/comments as
2436   // possible are retained from inline_unsafe_access though to make
2437   // the correspondences clearer. - dl
2438 
2439   if (callee()->is_static())  return false;  // caller must have the capability!
2440 
2441 #ifndef PRODUCT
2442   {
2443     ResourceMark rm;
2444     // Check the signatures.
2445     ciSignature* sig = signature();
2446 #ifdef ASSERT
2447     BasicType rtype = sig->return_type()->basic_type();
2448     assert(rtype == T_BOOLEAN, "CAS must return boolean");
2449     assert(sig->count() == 4, "CAS has 4 arguments");
2450     assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2451     assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2452 #endif // ASSERT
2453   }
2454 #endif //PRODUCT
2455 
2456   // number of stack slots per value argument (1 or 2)
2457   int type_words = type2size[type];
2458 
2459   // Cannot inline wide CAS on machines that don't support it natively
2460   if (type2aelembytes(type) > BytesPerInt && !VM_Version::supports_cx8())
2461     return false;
2462 
2463   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2464 
2465   // Argument words:  "this" plus oop plus offset plus oldvalue plus newvalue;
2466   int nargs = 1 + 1 + 2  + type_words + type_words;
2467 
2468   // pop arguments: newval, oldval, offset, base, and receiver
2469   debug_only(int saved_sp = _sp);
2470   _sp += nargs;
2471   Node* newval   = (type_words == 1) ? pop() : pop_pair();
2472   Node* oldval   = (type_words == 1) ? pop() : pop_pair();
2473   Node *offset   = pop_pair();
2474   Node *base     = pop();
2475   Node *receiver = pop();
2476   assert(saved_sp == _sp, "must have correct argument count");
2477 
2478   //  Null check receiver.
2479   _sp += nargs;
2480   do_null_check(receiver, T_OBJECT);
2481   _sp -= nargs;
2482   if (stopped()) {
2483     return true;
2484   }
2485 
2486   // Build field offset expression.
2487   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2488   // to be plain byte offsets, which are also the same as those accepted
2489   // by oopDesc::field_base.
2490   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2491   // 32-bit machines ignore the high half of long offsets
2492   offset = ConvL2X(offset);
2493   Node* adr = make_unsafe_address(base, offset);
2494   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2495 
2496   // (Unlike inline_unsafe_access, there seems no point in trying
2497   // to refine types. Just use the coarse types here.
2498   const Type *value_type = Type::get_const_basic_type(type);
2499   Compile::AliasType* alias_type = C->alias_type(adr_type);
2500   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2501   int alias_idx = C->get_alias_index(adr_type);
2502 
2503   // Memory-model-wise, a CAS acts like a little synchronized block,
2504   // so needs barriers on each side.  These don't translate into
2505   // actual barriers on most machines, but we still need rest of
2506   // compiler to respect ordering.
2507 
2508   insert_mem_bar(Op_MemBarRelease);
2509   insert_mem_bar(Op_MemBarCPUOrder);
2510 
2511   // 4984716: MemBars must be inserted before this
2512   //          memory node in order to avoid a false
2513   //          dependency which will confuse the scheduler.
2514   Node *mem = memory(alias_idx);
2515 
2516   // For now, we handle only those cases that actually exist: ints,
2517   // longs, and Object. Adding others should be straightforward.
2518   Node* cas;
2519   switch(type) {
2520   case T_INT:
2521     cas = _gvn.transform(new (C, 5) CompareAndSwapINode(control(), mem, adr, newval, oldval));
2522     break;
2523   case T_LONG:
2524     cas = _gvn.transform(new (C, 5) CompareAndSwapLNode(control(), mem, adr, newval, oldval));
2525     break;
2526   case T_OBJECT:
2527      // reference stores need a store barrier.
2528     // (They don't if CAS fails, but it isn't worth checking.)
2529     pre_barrier(control(), base, adr, alias_idx, newval, value_type->make_oopptr(), T_OBJECT);
2530 #ifdef _LP64
2531     if (adr->bottom_type()->is_ptr_to_narrowoop()) {
2532       Node *newval_enc = _gvn.transform(new (C, 2) EncodePNode(newval, newval->bottom_type()->make_narrowoop()));
2533       Node *oldval_enc = _gvn.transform(new (C, 2) EncodePNode(oldval, oldval->bottom_type()->make_narrowoop()));
2534       cas = _gvn.transform(new (C, 5) CompareAndSwapNNode(control(), mem, adr,
2535                                                           newval_enc, oldval_enc));
2536     } else
2537 #endif
2538     {
2539       cas = _gvn.transform(new (C, 5) CompareAndSwapPNode(control(), mem, adr, newval, oldval));
2540     }
2541     post_barrier(control(), cas, base, adr, alias_idx, newval, T_OBJECT, true);
2542     break;
2543   default:
2544     ShouldNotReachHere();
2545     break;
2546   }
2547 
2548   // SCMemProjNodes represent the memory state of CAS. Their main
2549   // role is to prevent CAS nodes from being optimized away when their
2550   // results aren't used.
2551   Node* proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
2552   set_memory(proj, alias_idx);
2553 
2554   // Add the trailing membar surrounding the access
2555   insert_mem_bar(Op_MemBarCPUOrder);
2556   insert_mem_bar(Op_MemBarAcquire);
2557 
2558   push(cas);
2559   return true;
2560 }
2561 
2562 bool LibraryCallKit::inline_unsafe_ordered_store(BasicType type) {
2563   // This is another variant of inline_unsafe_access, differing in
2564   // that it always issues store-store ("release") barrier and ensures
2565   // store-atomicity (which only matters for "long").
2566 
2567   if (callee()->is_static())  return false;  // caller must have the capability!
2568 
2569 #ifndef PRODUCT
2570   {
2571     ResourceMark rm;
2572     // Check the signatures.
2573     ciSignature* sig = signature();
2574 #ifdef ASSERT
2575     BasicType rtype = sig->return_type()->basic_type();
2576     assert(rtype == T_VOID, "must return void");
2577     assert(sig->count() == 3, "has 3 arguments");
2578     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base is object");
2579     assert(sig->type_at(1)->basic_type() == T_LONG, "offset is long");
2580 #endif // ASSERT
2581   }
2582 #endif //PRODUCT
2583 
2584   // number of stack slots per value argument (1 or 2)
2585   int type_words = type2size[type];
2586 
2587   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2588 
2589   // Argument words:  "this" plus oop plus offset plus value;
2590   int nargs = 1 + 1 + 2 + type_words;
2591 
2592   // pop arguments: val, offset, base, and receiver
2593   debug_only(int saved_sp = _sp);
2594   _sp += nargs;
2595   Node* val      = (type_words == 1) ? pop() : pop_pair();
2596   Node *offset   = pop_pair();
2597   Node *base     = pop();
2598   Node *receiver = pop();
2599   assert(saved_sp == _sp, "must have correct argument count");
2600 
2601   //  Null check receiver.
2602   _sp += nargs;
2603   do_null_check(receiver, T_OBJECT);
2604   _sp -= nargs;
2605   if (stopped()) {
2606     return true;
2607   }
2608 
2609   // Build field offset expression.
2610   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2611   // 32-bit machines ignore the high half of long offsets
2612   offset = ConvL2X(offset);
2613   Node* adr = make_unsafe_address(base, offset);
2614   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2615   const Type *value_type = Type::get_const_basic_type(type);
2616   Compile::AliasType* alias_type = C->alias_type(adr_type);
2617 
2618   insert_mem_bar(Op_MemBarRelease);
2619   insert_mem_bar(Op_MemBarCPUOrder);
2620   // Ensure that the store is atomic for longs:
2621   bool require_atomic_access = true;
2622   Node* store;
2623   if (type == T_OBJECT) // reference stores need a store barrier.
2624     store = store_oop_to_unknown(control(), base, adr, adr_type, val, type);
2625   else {
2626     store = store_to_memory(control(), adr, val, type, adr_type, require_atomic_access);
2627   }
2628   insert_mem_bar(Op_MemBarCPUOrder);
2629   return true;
2630 }
2631 
2632 bool LibraryCallKit::inline_unsafe_allocate() {
2633   if (callee()->is_static())  return false;  // caller must have the capability!
2634   int nargs = 1 + 1;
2635   assert(signature()->size() == nargs-1, "alloc has 1 argument");
2636   null_check_receiver(callee());  // check then ignore argument(0)
2637   _sp += nargs;  // set original stack for use by uncommon_trap
2638   Node* cls = do_null_check(argument(1), T_OBJECT);
2639   _sp -= nargs;
2640   if (stopped())  return true;
2641 
2642   Node* kls = load_klass_from_mirror(cls, false, nargs, NULL, 0);
2643   _sp += nargs;  // set original stack for use by uncommon_trap
2644   kls = do_null_check(kls, T_OBJECT);
2645   _sp -= nargs;
2646   if (stopped())  return true;  // argument was like int.class
2647 
2648   // Note:  The argument might still be an illegal value like
2649   // Serializable.class or Object[].class.   The runtime will handle it.
2650   // But we must make an explicit check for initialization.
2651   Node* insp = basic_plus_adr(kls, instanceKlass::init_state_offset_in_bytes() + sizeof(oopDesc));
2652   Node* inst = make_load(NULL, insp, TypeInt::INT, T_INT);
2653   Node* bits = intcon(instanceKlass::fully_initialized);
2654   Node* test = _gvn.transform( new (C, 3) SubINode(inst, bits) );
2655   // The 'test' is non-zero if we need to take a slow path.
2656 
2657   Node* obj = new_instance(kls, test);
2658   push(obj);
2659 
2660   return true;
2661 }
2662 
2663 //------------------------inline_native_time_funcs--------------
2664 // inline code for System.currentTimeMillis() and System.nanoTime()
2665 // these have the same type and signature
2666 bool LibraryCallKit::inline_native_time_funcs(bool isNano) {
2667   address funcAddr = isNano ? CAST_FROM_FN_PTR(address, os::javaTimeNanos) :
2668                               CAST_FROM_FN_PTR(address, os::javaTimeMillis);
2669   const char * funcName = isNano ? "nanoTime" : "currentTimeMillis";
2670   const TypeFunc *tf = OptoRuntime::current_time_millis_Type();
2671   const TypePtr* no_memory_effects = NULL;
2672   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2673   Node* value = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms+0));
2674 #ifdef ASSERT
2675   Node* value_top = _gvn.transform(new (C, 1) ProjNode(time, TypeFunc::Parms + 1));
2676   assert(value_top == top(), "second value must be top");
2677 #endif
2678   push_pair(value);
2679   return true;
2680 }
2681 
2682 //------------------------inline_native_currentThread------------------
2683 bool LibraryCallKit::inline_native_currentThread() {
2684   Node* junk = NULL;
2685   push(generate_current_thread(junk));
2686   return true;
2687 }
2688 
2689 //------------------------inline_native_isInterrupted------------------
2690 bool LibraryCallKit::inline_native_isInterrupted() {
2691   const int nargs = 1+1;  // receiver + boolean
2692   assert(nargs == arg_size(), "sanity");
2693   // Add a fast path to t.isInterrupted(clear_int):
2694   //   (t == Thread.current() && (!TLS._osthread._interrupted || !clear_int))
2695   //   ? TLS._osthread._interrupted : /*slow path:*/ t.isInterrupted(clear_int)
2696   // So, in the common case that the interrupt bit is false,
2697   // we avoid making a call into the VM.  Even if the interrupt bit
2698   // is true, if the clear_int argument is false, we avoid the VM call.
2699   // However, if the receiver is not currentThread, we must call the VM,
2700   // because there must be some locking done around the operation.
2701 
2702   // We only go to the fast case code if we pass two guards.
2703   // Paths which do not pass are accumulated in the slow_region.
2704   RegionNode* slow_region = new (C, 1) RegionNode(1);
2705   record_for_igvn(slow_region);
2706   RegionNode* result_rgn = new (C, 4) RegionNode(1+3); // fast1, fast2, slow
2707   PhiNode*    result_val = new (C, 4) PhiNode(result_rgn, TypeInt::BOOL);
2708   enum { no_int_result_path   = 1,
2709          no_clear_result_path = 2,
2710          slow_result_path     = 3
2711   };
2712 
2713   // (a) Receiving thread must be the current thread.
2714   Node* rec_thr = argument(0);
2715   Node* tls_ptr = NULL;
2716   Node* cur_thr = generate_current_thread(tls_ptr);
2717   Node* cmp_thr = _gvn.transform( new (C, 3) CmpPNode(cur_thr, rec_thr) );
2718   Node* bol_thr = _gvn.transform( new (C, 2) BoolNode(cmp_thr, BoolTest::ne) );
2719 
2720   bool known_current_thread = (_gvn.type(bol_thr) == TypeInt::ZERO);
2721   if (!known_current_thread)
2722     generate_slow_guard(bol_thr, slow_region);
2723 
2724   // (b) Interrupt bit on TLS must be false.
2725   Node* p = basic_plus_adr(top()/*!oop*/, tls_ptr, in_bytes(JavaThread::osthread_offset()));
2726   Node* osthread = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS);
2727   p = basic_plus_adr(top()/*!oop*/, osthread, in_bytes(OSThread::interrupted_offset()));
2728   // Set the control input on the field _interrupted read to prevent it floating up.
2729   Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT);
2730   Node* cmp_bit = _gvn.transform( new (C, 3) CmpINode(int_bit, intcon(0)) );
2731   Node* bol_bit = _gvn.transform( new (C, 2) BoolNode(cmp_bit, BoolTest::ne) );
2732 
2733   IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2734 
2735   // First fast path:  if (!TLS._interrupted) return false;
2736   Node* false_bit = _gvn.transform( new (C, 1) IfFalseNode(iff_bit) );
2737   result_rgn->init_req(no_int_result_path, false_bit);
2738   result_val->init_req(no_int_result_path, intcon(0));
2739 
2740   // drop through to next case
2741   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_bit)) );
2742 
2743   // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path.
2744   Node* clr_arg = argument(1);
2745   Node* cmp_arg = _gvn.transform( new (C, 3) CmpINode(clr_arg, intcon(0)) );
2746   Node* bol_arg = _gvn.transform( new (C, 2) BoolNode(cmp_arg, BoolTest::ne) );
2747   IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN);
2748 
2749   // Second fast path:  ... else if (!clear_int) return true;
2750   Node* false_arg = _gvn.transform( new (C, 1) IfFalseNode(iff_arg) );
2751   result_rgn->init_req(no_clear_result_path, false_arg);
2752   result_val->init_req(no_clear_result_path, intcon(1));
2753 
2754   // drop through to next case
2755   set_control( _gvn.transform(new (C, 1) IfTrueNode(iff_arg)) );
2756 
2757   // (d) Otherwise, go to the slow path.
2758   slow_region->add_req(control());
2759   set_control( _gvn.transform(slow_region) );
2760 
2761   if (stopped()) {
2762     // There is no slow path.
2763     result_rgn->init_req(slow_result_path, top());
2764     result_val->init_req(slow_result_path, top());
2765   } else {
2766     // non-virtual because it is a private non-static
2767     CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_isInterrupted);
2768 
2769     Node* slow_val = set_results_for_java_call(slow_call);
2770     // this->control() comes from set_results_for_java_call
2771 
2772     // If we know that the result of the slow call will be true, tell the optimizer!
2773     if (known_current_thread)  slow_val = intcon(1);
2774 
2775     Node* fast_io  = slow_call->in(TypeFunc::I_O);
2776     Node* fast_mem = slow_call->in(TypeFunc::Memory);
2777     // These two phis are pre-filled with copies of of the fast IO and Memory
2778     Node* io_phi   = PhiNode::make(result_rgn, fast_io,  Type::ABIO);
2779     Node* mem_phi  = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2780 
2781     result_rgn->init_req(slow_result_path, control());
2782     io_phi    ->init_req(slow_result_path, i_o());
2783     mem_phi   ->init_req(slow_result_path, reset_memory());
2784     result_val->init_req(slow_result_path, slow_val);
2785 
2786     set_all_memory( _gvn.transform(mem_phi) );
2787     set_i_o(        _gvn.transform(io_phi) );
2788   }
2789 
2790   push_result(result_rgn, result_val);
2791   C->set_has_split_ifs(true); // Has chance for split-if optimization
2792 
2793   return true;
2794 }
2795 
2796 //---------------------------load_mirror_from_klass----------------------------
2797 // Given a klass oop, load its java mirror (a java.lang.Class oop).
2798 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
2799   Node* p = basic_plus_adr(klass, Klass::java_mirror_offset_in_bytes() + sizeof(oopDesc));
2800   return make_load(NULL, p, TypeInstPtr::MIRROR, T_OBJECT);
2801 }
2802 
2803 //-----------------------load_klass_from_mirror_common-------------------------
2804 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
2805 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
2806 // and branch to the given path on the region.
2807 // If never_see_null, take an uncommon trap on null, so we can optimistically
2808 // compile for the non-null case.
2809 // If the region is NULL, force never_see_null = true.
2810 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
2811                                                     bool never_see_null,
2812                                                     int nargs,
2813                                                     RegionNode* region,
2814                                                     int null_path,
2815                                                     int offset) {
2816   if (region == NULL)  never_see_null = true;
2817   Node* p = basic_plus_adr(mirror, offset);
2818   const TypeKlassPtr*  kls_type = TypeKlassPtr::OBJECT_OR_NULL;
2819   Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type) );
2820   _sp += nargs; // any deopt will start just before call to enclosing method
2821   Node* null_ctl = top();
2822   kls = null_check_oop(kls, &null_ctl, never_see_null);
2823   if (region != NULL) {
2824     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
2825     region->init_req(null_path, null_ctl);
2826   } else {
2827     assert(null_ctl == top(), "no loose ends");
2828   }
2829   _sp -= nargs;
2830   return kls;
2831 }
2832 
2833 //--------------------(inline_native_Class_query helpers)---------------------
2834 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE, JVM_ACC_HAS_FINALIZER.
2835 // Fall through if (mods & mask) == bits, take the guard otherwise.
2836 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
2837   // Branch around if the given klass has the given modifier bit set.
2838   // Like generate_guard, adds a new path onto the region.
2839   Node* modp = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
2840   Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT);
2841   Node* mask = intcon(modifier_mask);
2842   Node* bits = intcon(modifier_bits);
2843   Node* mbit = _gvn.transform( new (C, 3) AndINode(mods, mask) );
2844   Node* cmp  = _gvn.transform( new (C, 3) CmpINode(mbit, bits) );
2845   Node* bol  = _gvn.transform( new (C, 2) BoolNode(cmp, BoolTest::ne) );
2846   return generate_fair_guard(bol, region);
2847 }
2848 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
2849   return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
2850 }
2851 
2852 //-------------------------inline_native_Class_query-------------------
2853 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
2854   int nargs = 1+0;  // just the Class mirror, in most cases
2855   const Type* return_type = TypeInt::BOOL;
2856   Node* prim_return_value = top();  // what happens if it's a primitive class?
2857   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
2858   bool expect_prim = false;     // most of these guys expect to work on refs
2859 
2860   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
2861 
2862   switch (id) {
2863   case vmIntrinsics::_isInstance:
2864     nargs = 1+1;  // the Class mirror, plus the object getting queried about
2865     // nothing is an instance of a primitive type
2866     prim_return_value = intcon(0);
2867     break;
2868   case vmIntrinsics::_getModifiers:
2869     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2870     assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
2871     return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
2872     break;
2873   case vmIntrinsics::_isInterface:
2874     prim_return_value = intcon(0);
2875     break;
2876   case vmIntrinsics::_isArray:
2877     prim_return_value = intcon(0);
2878     expect_prim = true;  // cf. ObjectStreamClass.getClassSignature
2879     break;
2880   case vmIntrinsics::_isPrimitive:
2881     prim_return_value = intcon(1);
2882     expect_prim = true;  // obviously
2883     break;
2884   case vmIntrinsics::_getSuperclass:
2885     prim_return_value = null();
2886     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
2887     break;
2888   case vmIntrinsics::_getComponentType:
2889     prim_return_value = null();
2890     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
2891     break;
2892   case vmIntrinsics::_getClassAccessFlags:
2893     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2894     return_type = TypeInt::INT;  // not bool!  6297094
2895     break;
2896   default:
2897     ShouldNotReachHere();
2898   }
2899 
2900   Node* mirror =                      argument(0);
2901   Node* obj    = (nargs <= 1)? top(): argument(1);
2902 
2903   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
2904   if (mirror_con == NULL)  return false;  // cannot happen?
2905 
2906 #ifndef PRODUCT
2907   if (PrintIntrinsics || PrintInlining || PrintOptoInlining) {
2908     ciType* k = mirror_con->java_mirror_type();
2909     if (k) {
2910       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
2911       k->print_name();
2912       tty->cr();
2913     }
2914   }
2915 #endif
2916 
2917   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
2918   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
2919   record_for_igvn(region);
2920   PhiNode* phi = new (C, PATH_LIMIT) PhiNode(region, return_type);
2921 
2922   // The mirror will never be null of Reflection.getClassAccessFlags, however
2923   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
2924   // if it is. See bug 4774291.
2925 
2926   // For Reflection.getClassAccessFlags(), the null check occurs in
2927   // the wrong place; see inline_unsafe_access(), above, for a similar
2928   // situation.
2929   _sp += nargs;  // set original stack for use by uncommon_trap
2930   mirror = do_null_check(mirror, T_OBJECT);
2931   _sp -= nargs;
2932   // If mirror or obj is dead, only null-path is taken.
2933   if (stopped())  return true;
2934 
2935   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
2936 
2937   // Now load the mirror's klass metaobject, and null-check it.
2938   // Side-effects region with the control path if the klass is null.
2939   Node* kls = load_klass_from_mirror(mirror, never_see_null, nargs,
2940                                      region, _prim_path);
2941   // If kls is null, we have a primitive mirror.
2942   phi->init_req(_prim_path, prim_return_value);
2943   if (stopped()) { push_result(region, phi); return true; }
2944 
2945   Node* p;  // handy temp
2946   Node* null_ctl;
2947 
2948   // Now that we have the non-null klass, we can perform the real query.
2949   // For constant classes, the query will constant-fold in LoadNode::Value.
2950   Node* query_value = top();
2951   switch (id) {
2952   case vmIntrinsics::_isInstance:
2953     // nothing is an instance of a primitive type
2954     _sp += nargs;          // gen_instanceof might do an uncommon trap
2955     query_value = gen_instanceof(obj, kls);
2956     _sp -= nargs;
2957     break;
2958 
2959   case vmIntrinsics::_getModifiers:
2960     p = basic_plus_adr(kls, Klass::modifier_flags_offset_in_bytes() + sizeof(oopDesc));
2961     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
2962     break;
2963 
2964   case vmIntrinsics::_isInterface:
2965     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
2966     if (generate_interface_guard(kls, region) != NULL)
2967       // A guard was added.  If the guard is taken, it was an interface.
2968       phi->add_req(intcon(1));
2969     // If we fall through, it's a plain class.
2970     query_value = intcon(0);
2971     break;
2972 
2973   case vmIntrinsics::_isArray:
2974     // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
2975     if (generate_array_guard(kls, region) != NULL)
2976       // A guard was added.  If the guard is taken, it was an array.
2977       phi->add_req(intcon(1));
2978     // If we fall through, it's a plain class.
2979     query_value = intcon(0);
2980     break;
2981 
2982   case vmIntrinsics::_isPrimitive:
2983     query_value = intcon(0); // "normal" path produces false
2984     break;
2985 
2986   case vmIntrinsics::_getSuperclass:
2987     // The rules here are somewhat unfortunate, but we can still do better
2988     // with random logic than with a JNI call.
2989     // Interfaces store null or Object as _super, but must report null.
2990     // Arrays store an intermediate super as _super, but must report Object.
2991     // Other types can report the actual _super.
2992     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
2993     if (generate_interface_guard(kls, region) != NULL)
2994       // A guard was added.  If the guard is taken, it was an interface.
2995       phi->add_req(null());
2996     if (generate_array_guard(kls, region) != NULL)
2997       // A guard was added.  If the guard is taken, it was an array.
2998       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
2999     // If we fall through, it's a plain class.  Get its _super.
3000     p = basic_plus_adr(kls, Klass::super_offset_in_bytes() + sizeof(oopDesc));
3001     kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL) );
3002     null_ctl = top();
3003     kls = null_check_oop(kls, &null_ctl);
3004     if (null_ctl != top()) {
3005       // If the guard is taken, Object.superClass is null (both klass and mirror).
3006       region->add_req(null_ctl);
3007       phi   ->add_req(null());
3008     }
3009     if (!stopped()) {
3010       query_value = load_mirror_from_klass(kls);
3011     }
3012     break;
3013 
3014   case vmIntrinsics::_getComponentType:
3015     if (generate_array_guard(kls, region) != NULL) {
3016       // Be sure to pin the oop load to the guard edge just created:
3017       Node* is_array_ctrl = region->in(region->req()-1);
3018       Node* cma = basic_plus_adr(kls, in_bytes(arrayKlass::component_mirror_offset()) + sizeof(oopDesc));
3019       Node* cmo = make_load(is_array_ctrl, cma, TypeInstPtr::MIRROR, T_OBJECT);
3020       phi->add_req(cmo);
3021     }
3022     query_value = null();  // non-array case is null
3023     break;
3024 
3025   case vmIntrinsics::_getClassAccessFlags:
3026     p = basic_plus_adr(kls, Klass::access_flags_offset_in_bytes() + sizeof(oopDesc));
3027     query_value = make_load(NULL, p, TypeInt::INT, T_INT);
3028     break;
3029 
3030   default:
3031     ShouldNotReachHere();
3032   }
3033 
3034   // Fall-through is the normal case of a query to a real class.
3035   phi->init_req(1, query_value);
3036   region->init_req(1, control());
3037 
3038   push_result(region, phi);
3039   C->set_has_split_ifs(true); // Has chance for split-if optimization
3040 
3041   return true;
3042 }
3043 
3044 //--------------------------inline_native_subtype_check------------------------
3045 // This intrinsic takes the JNI calls out of the heart of
3046 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
3047 bool LibraryCallKit::inline_native_subtype_check() {
3048   int nargs = 1+1;  // the Class mirror, plus the other class getting examined
3049 
3050   // Pull both arguments off the stack.
3051   Node* args[2];                // two java.lang.Class mirrors: superc, subc
3052   args[0] = argument(0);
3053   args[1] = argument(1);
3054   Node* klasses[2];             // corresponding Klasses: superk, subk
3055   klasses[0] = klasses[1] = top();
3056 
3057   enum {
3058     // A full decision tree on {superc is prim, subc is prim}:
3059     _prim_0_path = 1,           // {P,N} => false
3060                                 // {P,P} & superc!=subc => false
3061     _prim_same_path,            // {P,P} & superc==subc => true
3062     _prim_1_path,               // {N,P} => false
3063     _ref_subtype_path,          // {N,N} & subtype check wins => true
3064     _both_ref_path,             // {N,N} & subtype check loses => false
3065     PATH_LIMIT
3066   };
3067 
3068   RegionNode* region = new (C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3069   Node*       phi    = new (C, PATH_LIMIT) PhiNode(region, TypeInt::BOOL);
3070   record_for_igvn(region);
3071 
3072   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
3073   const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3074   int class_klass_offset = java_lang_Class::klass_offset_in_bytes();
3075 
3076   // First null-check both mirrors and load each mirror's klass metaobject.
3077   int which_arg;
3078   for (which_arg = 0; which_arg <= 1; which_arg++) {
3079     Node* arg = args[which_arg];
3080     _sp += nargs;  // set original stack for use by uncommon_trap
3081     arg = do_null_check(arg, T_OBJECT);
3082     _sp -= nargs;
3083     if (stopped())  break;
3084     args[which_arg] = _gvn.transform(arg);
3085 
3086     Node* p = basic_plus_adr(arg, class_klass_offset);
3087     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
3088     klasses[which_arg] = _gvn.transform(kls);
3089   }
3090 
3091   // Having loaded both klasses, test each for null.
3092   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3093   for (which_arg = 0; which_arg <= 1; which_arg++) {
3094     Node* kls = klasses[which_arg];
3095     Node* null_ctl = top();
3096     _sp += nargs;  // set original stack for use by uncommon_trap
3097     kls = null_check_oop(kls, &null_ctl, never_see_null);
3098     _sp -= nargs;
3099     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3100     region->init_req(prim_path, null_ctl);
3101     if (stopped())  break;
3102     klasses[which_arg] = kls;
3103   }
3104 
3105   if (!stopped()) {
3106     // now we have two reference types, in klasses[0..1]
3107     Node* subk   = klasses[1];  // the argument to isAssignableFrom
3108     Node* superk = klasses[0];  // the receiver
3109     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3110     // now we have a successful reference subtype check
3111     region->set_req(_ref_subtype_path, control());
3112   }
3113 
3114   // If both operands are primitive (both klasses null), then
3115   // we must return true when they are identical primitives.
3116   // It is convenient to test this after the first null klass check.
3117   set_control(region->in(_prim_0_path)); // go back to first null check
3118   if (!stopped()) {
3119     // Since superc is primitive, make a guard for the superc==subc case.
3120     Node* cmp_eq = _gvn.transform( new (C, 3) CmpPNode(args[0], args[1]) );
3121     Node* bol_eq = _gvn.transform( new (C, 2) BoolNode(cmp_eq, BoolTest::eq) );
3122     generate_guard(bol_eq, region, PROB_FAIR);
3123     if (region->req() == PATH_LIMIT+1) {
3124       // A guard was added.  If the added guard is taken, superc==subc.
3125       region->swap_edges(PATH_LIMIT, _prim_same_path);
3126       region->del_req(PATH_LIMIT);
3127     }
3128     region->set_req(_prim_0_path, control()); // Not equal after all.
3129   }
3130 
3131   // these are the only paths that produce 'true':
3132   phi->set_req(_prim_same_path,   intcon(1));
3133   phi->set_req(_ref_subtype_path, intcon(1));
3134 
3135   // pull together the cases:
3136   assert(region->req() == PATH_LIMIT, "sane region");
3137   for (uint i = 1; i < region->req(); i++) {
3138     Node* ctl = region->in(i);
3139     if (ctl == NULL || ctl == top()) {
3140       region->set_req(i, top());
3141       phi   ->set_req(i, top());
3142     } else if (phi->in(i) == NULL) {
3143       phi->set_req(i, intcon(0)); // all other paths produce 'false'
3144     }
3145   }
3146 
3147   set_control(_gvn.transform(region));
3148   push(_gvn.transform(phi));
3149 
3150   return true;
3151 }
3152 
3153 //---------------------generate_array_guard_common------------------------
3154 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3155                                                   bool obj_array, bool not_array) {
3156   // If obj_array/non_array==false/false:
3157   // Branch around if the given klass is in fact an array (either obj or prim).
3158   // If obj_array/non_array==false/true:
3159   // Branch around if the given klass is not an array klass of any kind.
3160   // If obj_array/non_array==true/true:
3161   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3162   // If obj_array/non_array==true/false:
3163   // Branch around if the kls is an oop array (Object[] or subtype)
3164   //
3165   // Like generate_guard, adds a new path onto the region.
3166   jint  layout_con = 0;
3167   Node* layout_val = get_layout_helper(kls, layout_con);
3168   if (layout_val == NULL) {
3169     bool query = (obj_array
3170                   ? Klass::layout_helper_is_objArray(layout_con)
3171                   : Klass::layout_helper_is_javaArray(layout_con));
3172     if (query == not_array) {
3173       return NULL;                       // never a branch
3174     } else {                             // always a branch
3175       Node* always_branch = control();
3176       if (region != NULL)
3177         region->add_req(always_branch);
3178       set_control(top());
3179       return always_branch;
3180     }
3181   }
3182   // Now test the correct condition.
3183   jint  nval = (obj_array
3184                 ? ((jint)Klass::_lh_array_tag_type_value
3185                    <<    Klass::_lh_array_tag_shift)
3186                 : Klass::_lh_neutral_value);
3187   Node* cmp = _gvn.transform( new(C, 3) CmpINode(layout_val, intcon(nval)) );
3188   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
3189   // invert the test if we are looking for a non-array
3190   if (not_array)  btest = BoolTest(btest).negate();
3191   Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, btest) );
3192   return generate_fair_guard(bol, region);
3193 }
3194 
3195 
3196 //-----------------------inline_native_newArray--------------------------
3197 bool LibraryCallKit::inline_native_newArray() {
3198   int nargs = 2;
3199   Node* mirror    = argument(0);
3200   Node* count_val = argument(1);
3201 
3202   _sp += nargs;  // set original stack for use by uncommon_trap
3203   mirror = do_null_check(mirror, T_OBJECT);
3204   _sp -= nargs;
3205   // If mirror or obj is dead, only null-path is taken.
3206   if (stopped())  return true;
3207 
3208   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3209   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3210   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
3211                                                       TypeInstPtr::NOTNULL);
3212   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
3213   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
3214                                                       TypePtr::BOTTOM);
3215 
3216   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3217   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3218                                                   nargs,
3219                                                   result_reg, _slow_path);
3220   Node* normal_ctl   = control();
3221   Node* no_array_ctl = result_reg->in(_slow_path);
3222 
3223   // Generate code for the slow case.  We make a call to newArray().
3224   set_control(no_array_ctl);
3225   if (!stopped()) {
3226     // Either the input type is void.class, or else the
3227     // array klass has not yet been cached.  Either the
3228     // ensuing call will throw an exception, or else it
3229     // will cache the array klass for next time.
3230     PreserveJVMState pjvms(this);
3231     CallJavaNode* slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3232     Node* slow_result = set_results_for_java_call(slow_call);
3233     // this->control() comes from set_results_for_java_call
3234     result_reg->set_req(_slow_path, control());
3235     result_val->set_req(_slow_path, slow_result);
3236     result_io ->set_req(_slow_path, i_o());
3237     result_mem->set_req(_slow_path, reset_memory());
3238   }
3239 
3240   set_control(normal_ctl);
3241   if (!stopped()) {
3242     // Normal case:  The array type has been cached in the java.lang.Class.
3243     // The following call works fine even if the array type is polymorphic.
3244     // It could be a dynamic mix of int[], boolean[], Object[], etc.
3245     Node* obj = new_array(klass_node, count_val, nargs);
3246     result_reg->init_req(_normal_path, control());
3247     result_val->init_req(_normal_path, obj);
3248     result_io ->init_req(_normal_path, i_o());
3249     result_mem->init_req(_normal_path, reset_memory());
3250   }
3251 
3252   // Return the combined state.
3253   set_i_o(        _gvn.transform(result_io)  );
3254   set_all_memory( _gvn.transform(result_mem) );
3255   push_result(result_reg, result_val);
3256   C->set_has_split_ifs(true); // Has chance for split-if optimization
3257 
3258   return true;
3259 }
3260 
3261 //----------------------inline_native_getLength--------------------------
3262 bool LibraryCallKit::inline_native_getLength() {
3263   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3264 
3265   int nargs = 1;
3266   Node* array = argument(0);
3267 
3268   _sp += nargs;  // set original stack for use by uncommon_trap
3269   array = do_null_check(array, T_OBJECT);
3270   _sp -= nargs;
3271 
3272   // If array is dead, only null-path is taken.
3273   if (stopped())  return true;
3274 
3275   // Deoptimize if it is a non-array.
3276   Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3277 
3278   if (non_array != NULL) {
3279     PreserveJVMState pjvms(this);
3280     set_control(non_array);
3281     _sp += nargs;  // push the arguments back on the stack
3282     uncommon_trap(Deoptimization::Reason_intrinsic,
3283                   Deoptimization::Action_maybe_recompile);
3284   }
3285 
3286   // If control is dead, only non-array-path is taken.
3287   if (stopped())  return true;
3288 
3289   // The works fine even if the array type is polymorphic.
3290   // It could be a dynamic mix of int[], boolean[], Object[], etc.
3291   push( load_array_length(array) );
3292 
3293   C->set_has_split_ifs(true); // Has chance for split-if optimization
3294 
3295   return true;
3296 }
3297 
3298 //------------------------inline_array_copyOf----------------------------
3299 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3300   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
3301 
3302   // Restore the stack and pop off the arguments.
3303   int nargs = 3 + (is_copyOfRange? 1: 0);
3304   Node* original          = argument(0);
3305   Node* start             = is_copyOfRange? argument(1): intcon(0);
3306   Node* end               = is_copyOfRange? argument(2): argument(1);
3307   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3308 
3309   Node* newcopy;
3310 
3311   //set the original stack and the reexecute bit for the interpreter to reexecute
3312   //the bytecode that invokes Arrays.copyOf if deoptimization happens
3313   { PreserveReexecuteState preexecs(this);
3314     _sp += nargs;
3315     jvms()->set_should_reexecute(true);
3316 
3317     array_type_mirror = do_null_check(array_type_mirror, T_OBJECT);
3318     original          = do_null_check(original, T_OBJECT);
3319 
3320     // Check if a null path was taken unconditionally.
3321     if (stopped())  return true;
3322 
3323     Node* orig_length = load_array_length(original);
3324 
3325     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, 0,
3326                                               NULL, 0);
3327     klass_node = do_null_check(klass_node, T_OBJECT);
3328 
3329     RegionNode* bailout = new (C, 1) RegionNode(1);
3330     record_for_igvn(bailout);
3331 
3332     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3333     // Bail out if that is so.
3334     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3335     if (not_objArray != NULL) {
3336       // Improve the klass node's type from the new optimistic assumption:
3337       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3338       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3339       Node* cast = new (C, 2) CastPPNode(klass_node, akls);
3340       cast->init_req(0, control());
3341       klass_node = _gvn.transform(cast);
3342     }
3343 
3344     // Bail out if either start or end is negative.
3345     generate_negative_guard(start, bailout, &start);
3346     generate_negative_guard(end,   bailout, &end);
3347 
3348     Node* length = end;
3349     if (_gvn.type(start) != TypeInt::ZERO) {
3350       length = _gvn.transform( new (C, 3) SubINode(end, start) );
3351     }
3352 
3353     // Bail out if length is negative.
3354     // ...Not needed, since the new_array will throw the right exception.
3355     //generate_negative_guard(length, bailout, &length);
3356 
3357     if (bailout->req() > 1) {
3358       PreserveJVMState pjvms(this);
3359       set_control( _gvn.transform(bailout) );
3360       uncommon_trap(Deoptimization::Reason_intrinsic,
3361                     Deoptimization::Action_maybe_recompile);
3362     }
3363 
3364     if (!stopped()) {
3365 
3366       // How many elements will we copy from the original?
3367       // The answer is MinI(orig_length - start, length).
3368       Node* orig_tail = _gvn.transform( new(C, 3) SubINode(orig_length, start) );
3369       Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3370 
3371       const bool raw_mem_only = true;
3372       newcopy = new_array(klass_node, length, 0, raw_mem_only);
3373 
3374       // Generate a direct call to the right arraycopy function(s).
3375       // We know the copy is disjoint but we might not know if the
3376       // oop stores need checking.
3377       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
3378       // This will fail a store-check if x contains any non-nulls.
3379       bool disjoint_bases = true;
3380       bool length_never_negative = true;
3381       generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
3382                          original, start, newcopy, intcon(0), moved,
3383                          disjoint_bases, length_never_negative);
3384     }
3385   } //original reexecute and sp are set back here
3386 
3387   if(!stopped()) {
3388     push(newcopy);
3389   }
3390 
3391   C->set_has_split_ifs(true); // Has chance for split-if optimization
3392 
3393   return true;
3394 }
3395 
3396 
3397 //----------------------generate_virtual_guard---------------------------
3398 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
3399 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
3400                                              RegionNode* slow_region) {
3401   ciMethod* method = callee();
3402   int vtable_index = method->vtable_index();
3403   // Get the methodOop out of the appropriate vtable entry.
3404   int entry_offset  = (instanceKlass::vtable_start_offset() +
3405                      vtable_index*vtableEntry::size()) * wordSize +
3406                      vtableEntry::method_offset_in_bytes();
3407   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
3408   Node* target_call = make_load(NULL, entry_addr, TypeInstPtr::NOTNULL, T_OBJECT);
3409 
3410   // Compare the target method with the expected method (e.g., Object.hashCode).
3411   const TypeInstPtr* native_call_addr = TypeInstPtr::make(method);
3412 
3413   Node* native_call = makecon(native_call_addr);
3414   Node* chk_native  = _gvn.transform( new(C, 3) CmpPNode(target_call, native_call) );
3415   Node* test_native = _gvn.transform( new(C, 2) BoolNode(chk_native, BoolTest::ne) );
3416 
3417   return generate_slow_guard(test_native, slow_region);
3418 }
3419 
3420 //-----------------------generate_method_call----------------------------
3421 // Use generate_method_call to make a slow-call to the real
3422 // method if the fast path fails.  An alternative would be to
3423 // use a stub like OptoRuntime::slow_arraycopy_Java.
3424 // This only works for expanding the current library call,
3425 // not another intrinsic.  (E.g., don't use this for making an
3426 // arraycopy call inside of the copyOf intrinsic.)
3427 CallJavaNode*
3428 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
3429   // When compiling the intrinsic method itself, do not use this technique.
3430   guarantee(callee() != C->method(), "cannot make slow-call to self");
3431 
3432   ciMethod* method = callee();
3433   // ensure the JVMS we have will be correct for this call
3434   guarantee(method_id == method->intrinsic_id(), "must match");
3435 
3436   const TypeFunc* tf = TypeFunc::make(method);
3437   int tfdc = tf->domain()->cnt();
3438   CallJavaNode* slow_call;
3439   if (is_static) {
3440     assert(!is_virtual, "");
3441     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
3442                                 SharedRuntime::get_resolve_static_call_stub(),
3443                                 method, bci());
3444   } else if (is_virtual) {
3445     null_check_receiver(method);
3446     int vtable_index = methodOopDesc::invalid_vtable_index;
3447     if (UseInlineCaches) {
3448       // Suppress the vtable call
3449     } else {
3450       // hashCode and clone are not a miranda methods,
3451       // so the vtable index is fixed.
3452       // No need to use the linkResolver to get it.
3453        vtable_index = method->vtable_index();
3454     }
3455     slow_call = new(C, tfdc) CallDynamicJavaNode(tf,
3456                                 SharedRuntime::get_resolve_virtual_call_stub(),
3457                                 method, vtable_index, bci());
3458   } else {  // neither virtual nor static:  opt_virtual
3459     null_check_receiver(method);
3460     slow_call = new(C, tfdc) CallStaticJavaNode(tf,
3461                                 SharedRuntime::get_resolve_opt_virtual_call_stub(),
3462                                 method, bci());
3463     slow_call->set_optimized_virtual(true);
3464   }
3465   set_arguments_for_java_call(slow_call);
3466   set_edges_for_java_call(slow_call);
3467   return slow_call;
3468 }
3469 
3470 
3471 //------------------------------inline_native_hashcode--------------------
3472 // Build special case code for calls to hashCode on an object.
3473 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
3474   assert(is_static == callee()->is_static(), "correct intrinsic selection");
3475   assert(!(is_virtual && is_static), "either virtual, special, or static");
3476 
3477   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
3478 
3479   RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
3480   PhiNode*    result_val = new(C, PATH_LIMIT) PhiNode(result_reg,
3481                                                       TypeInt::INT);
3482   PhiNode*    result_io  = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
3483   PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
3484                                                       TypePtr::BOTTOM);
3485   Node* obj = NULL;
3486   if (!is_static) {
3487     // Check for hashing null object
3488     obj = null_check_receiver(callee());
3489     if (stopped())  return true;        // unconditionally null
3490     result_reg->init_req(_null_path, top());
3491     result_val->init_req(_null_path, top());
3492   } else {
3493     // Do a null check, and return zero if null.
3494     // System.identityHashCode(null) == 0
3495     obj = argument(0);
3496     Node* null_ctl = top();
3497     obj = null_check_oop(obj, &null_ctl);
3498     result_reg->init_req(_null_path, null_ctl);
3499     result_val->init_req(_null_path, _gvn.intcon(0));
3500   }
3501 
3502   // Unconditionally null?  Then return right away.
3503   if (stopped()) {
3504     set_control( result_reg->in(_null_path) );
3505     if (!stopped())
3506       push(      result_val ->in(_null_path) );
3507     return true;
3508   }
3509 
3510   // After null check, get the object's klass.
3511   Node* obj_klass = load_object_klass(obj);
3512 
3513   // This call may be virtual (invokevirtual) or bound (invokespecial).
3514   // For each case we generate slightly different code.
3515 
3516   // We only go to the fast case code if we pass a number of guards.  The
3517   // paths which do not pass are accumulated in the slow_region.
3518   RegionNode* slow_region = new (C, 1) RegionNode(1);
3519   record_for_igvn(slow_region);
3520 
3521   // If this is a virtual call, we generate a funny guard.  We pull out
3522   // the vtable entry corresponding to hashCode() from the target object.
3523   // If the target method which we are calling happens to be the native
3524   // Object hashCode() method, we pass the guard.  We do not need this
3525   // guard for non-virtual calls -- the caller is known to be the native
3526   // Object hashCode().
3527   if (is_virtual) {
3528     generate_virtual_guard(obj_klass, slow_region);
3529   }
3530 
3531   // Get the header out of the object, use LoadMarkNode when available
3532   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3533   Node* header = make_load(control(), header_addr, TypeX_X, TypeX_X->basic_type());
3534 
3535   // Test the header to see if it is unlocked.
3536   Node *lock_mask      = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place);
3537   Node *lmasked_header = _gvn.transform( new (C, 3) AndXNode(header, lock_mask) );
3538   Node *unlocked_val   = _gvn.MakeConX(markOopDesc::unlocked_value);
3539   Node *chk_unlocked   = _gvn.transform( new (C, 3) CmpXNode( lmasked_header, unlocked_val));
3540   Node *test_unlocked  = _gvn.transform( new (C, 2) BoolNode( chk_unlocked, BoolTest::ne) );
3541 
3542   generate_slow_guard(test_unlocked, slow_region);
3543 
3544   // Get the hash value and check to see that it has been properly assigned.
3545   // We depend on hash_mask being at most 32 bits and avoid the use of
3546   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
3547   // vm: see markOop.hpp.
3548   Node *hash_mask      = _gvn.intcon(markOopDesc::hash_mask);
3549   Node *hash_shift     = _gvn.intcon(markOopDesc::hash_shift);
3550   Node *hshifted_header= _gvn.transform( new (C, 3) URShiftXNode(header, hash_shift) );
3551   // This hack lets the hash bits live anywhere in the mark object now, as long
3552   // as the shift drops the relevant bits into the low 32 bits.  Note that
3553   // Java spec says that HashCode is an int so there's no point in capturing
3554   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
3555   hshifted_header      = ConvX2I(hshifted_header);
3556   Node *hash_val       = _gvn.transform( new (C, 3) AndINode(hshifted_header, hash_mask) );
3557 
3558   Node *no_hash_val    = _gvn.intcon(markOopDesc::no_hash);
3559   Node *chk_assigned   = _gvn.transform( new (C, 3) CmpINode( hash_val, no_hash_val));
3560   Node *test_assigned  = _gvn.transform( new (C, 2) BoolNode( chk_assigned, BoolTest::eq) );
3561 
3562   generate_slow_guard(test_assigned, slow_region);
3563 
3564   Node* init_mem = reset_memory();
3565   // fill in the rest of the null path:
3566   result_io ->init_req(_null_path, i_o());
3567   result_mem->init_req(_null_path, init_mem);
3568 
3569   result_val->init_req(_fast_path, hash_val);
3570   result_reg->init_req(_fast_path, control());
3571   result_io ->init_req(_fast_path, i_o());
3572   result_mem->init_req(_fast_path, init_mem);
3573 
3574   // Generate code for the slow case.  We make a call to hashCode().
3575   set_control(_gvn.transform(slow_region));
3576   if (!stopped()) {
3577     // No need for PreserveJVMState, because we're using up the present state.
3578     set_all_memory(init_mem);
3579     vmIntrinsics::ID hashCode_id = vmIntrinsics::_hashCode;
3580     if (is_static)   hashCode_id = vmIntrinsics::_identityHashCode;
3581     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
3582     Node* slow_result = set_results_for_java_call(slow_call);
3583     // this->control() comes from set_results_for_java_call
3584     result_reg->init_req(_slow_path, control());
3585     result_val->init_req(_slow_path, slow_result);
3586     result_io  ->set_req(_slow_path, i_o());
3587     result_mem ->set_req(_slow_path, reset_memory());
3588   }
3589 
3590   // Return the combined state.
3591   set_i_o(        _gvn.transform(result_io)  );
3592   set_all_memory( _gvn.transform(result_mem) );
3593   push_result(result_reg, result_val);
3594 
3595   return true;
3596 }
3597 
3598 //---------------------------inline_native_getClass----------------------------
3599 // Build special case code for calls to getClass on an object.
3600 bool LibraryCallKit::inline_native_getClass() {
3601   Node* obj = null_check_receiver(callee());
3602   if (stopped())  return true;
3603   push( load_mirror_from_klass(load_object_klass(obj)) );
3604   return true;
3605 }
3606 
3607 //-----------------inline_native_Reflection_getCallerClass---------------------
3608 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
3609 //
3610 // NOTE that this code must perform the same logic as
3611 // vframeStream::security_get_caller_frame in that it must skip
3612 // Method.invoke() and auxiliary frames.
3613 
3614 
3615 
3616 
3617 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
3618   ciMethod*       method = callee();
3619 
3620 #ifndef PRODUCT
3621   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3622     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
3623   }
3624 #endif
3625 
3626   debug_only(int saved_sp = _sp);
3627 
3628   // Argument words:  (int depth)
3629   int nargs = 1;
3630 
3631   _sp += nargs;
3632   Node* caller_depth_node = pop();
3633 
3634   assert(saved_sp == _sp, "must have correct argument count");
3635 
3636   // The depth value must be a constant in order for the runtime call
3637   // to be eliminated.
3638   const TypeInt* caller_depth_type = _gvn.type(caller_depth_node)->isa_int();
3639   if (caller_depth_type == NULL || !caller_depth_type->is_con()) {
3640 #ifndef PRODUCT
3641     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3642       tty->print_cr("  Bailing out because caller depth was not a constant");
3643     }
3644 #endif
3645     return false;
3646   }
3647   // Note that the JVM state at this point does not include the
3648   // getCallerClass() frame which we are trying to inline. The
3649   // semantics of getCallerClass(), however, are that the "first"
3650   // frame is the getCallerClass() frame, so we subtract one from the
3651   // requested depth before continuing. We don't inline requests of
3652   // getCallerClass(0).
3653   int caller_depth = caller_depth_type->get_con() - 1;
3654   if (caller_depth < 0) {
3655 #ifndef PRODUCT
3656     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3657       tty->print_cr("  Bailing out because caller depth was %d", caller_depth);
3658     }
3659 #endif
3660     return false;
3661   }
3662 
3663   if (!jvms()->has_method()) {
3664 #ifndef PRODUCT
3665     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3666       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
3667     }
3668 #endif
3669     return false;
3670   }
3671   int _depth = jvms()->depth();  // cache call chain depth
3672 
3673   // Walk back up the JVM state to find the caller at the required
3674   // depth. NOTE that this code must perform the same logic as
3675   // vframeStream::security_get_caller_frame in that it must skip
3676   // Method.invoke() and auxiliary frames. Note also that depth is
3677   // 1-based (1 is the bottom of the inlining).
3678   int inlining_depth = _depth;
3679   JVMState* caller_jvms = NULL;
3680 
3681   if (inlining_depth > 0) {
3682     caller_jvms = jvms();
3683     assert(caller_jvms = jvms()->of_depth(inlining_depth), "inlining_depth == our depth");
3684     do {
3685       // The following if-tests should be performed in this order
3686       if (is_method_invoke_or_aux_frame(caller_jvms)) {
3687         // Skip a Method.invoke() or auxiliary frame
3688       } else if (caller_depth > 0) {
3689         // Skip real frame
3690         --caller_depth;
3691       } else {
3692         // We're done: reached desired caller after skipping.
3693         break;
3694       }
3695       caller_jvms = caller_jvms->caller();
3696       --inlining_depth;
3697     } while (inlining_depth > 0);
3698   }
3699 
3700   if (inlining_depth == 0) {
3701 #ifndef PRODUCT
3702     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3703       tty->print_cr("  Bailing out because caller depth (%d) exceeded inlining depth (%d)", caller_depth_type->get_con(), _depth);
3704       tty->print_cr("  JVM state at this point:");
3705       for (int i = _depth; i >= 1; i--) {
3706         tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
3707       }
3708     }
3709 #endif
3710     return false; // Reached end of inlining
3711   }
3712 
3713   // Acquire method holder as java.lang.Class
3714   ciInstanceKlass* caller_klass  = caller_jvms->method()->holder();
3715   ciInstance*      caller_mirror = caller_klass->java_mirror();
3716   // Push this as a constant
3717   push(makecon(TypeInstPtr::make(caller_mirror)));
3718 #ifndef PRODUCT
3719   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
3720     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);
3721     tty->print_cr("  JVM state at this point:");
3722     for (int i = _depth; i >= 1; i--) {
3723       tty->print_cr("   %d) %s", i, jvms()->of_depth(i)->method()->name()->as_utf8());
3724     }
3725   }
3726 #endif
3727   return true;
3728 }
3729 
3730 // Helper routine for above
3731 bool LibraryCallKit::is_method_invoke_or_aux_frame(JVMState* jvms) {
3732   ciMethod* method = jvms->method();
3733 
3734   // Is this the Method.invoke method itself?
3735   if (method->intrinsic_id() == vmIntrinsics::_invoke)
3736     return true;
3737 
3738   // Is this a helper, defined somewhere underneath MethodAccessorImpl.
3739   ciKlass* k = method->holder();
3740   if (k->is_instance_klass()) {
3741     ciInstanceKlass* ik = k->as_instance_klass();
3742     for (; ik != NULL; ik = ik->super()) {
3743       if (ik->name() == ciSymbol::sun_reflect_MethodAccessorImpl() &&
3744           ik == env()->find_system_klass(ik->name())) {
3745         return true;
3746       }
3747     }
3748   }
3749   else if (method->is_method_handle_adapter()) {
3750     // This is an internal adapter frame from the MethodHandleCompiler -- skip it
3751     return true;
3752   }
3753 
3754   return false;
3755 }
3756 
3757 static int value_field_offset = -1;  // offset of the "value" field of AtomicLongCSImpl.  This is needed by
3758                                      // inline_native_AtomicLong_attemptUpdate() but it has no way of
3759                                      // computing it since there is no lookup field by name function in the
3760                                      // CI interface.  This is computed and set by inline_native_AtomicLong_get().
3761                                      // Using a static variable here is safe even if we have multiple compilation
3762                                      // threads because the offset is constant.  At worst the same offset will be
3763                                      // computed and  stored multiple
3764 
3765 bool LibraryCallKit::inline_native_AtomicLong_get() {
3766   // Restore the stack and pop off the argument
3767   _sp+=1;
3768   Node *obj = pop();
3769 
3770   // get the offset of the "value" field. Since the CI interfaces
3771   // does not provide a way to look up a field by name, we scan the bytecodes
3772   // to get the field index.  We expect the first 2 instructions of the method
3773   // to be:
3774   //    0 aload_0
3775   //    1 getfield "value"
3776   ciMethod* method = callee();
3777   if (value_field_offset == -1)
3778   {
3779     ciField* value_field;
3780     ciBytecodeStream iter(method);
3781     Bytecodes::Code bc = iter.next();
3782 
3783     if ((bc != Bytecodes::_aload_0) &&
3784               ((bc != Bytecodes::_aload) || (iter.get_index() != 0)))
3785       return false;
3786     bc = iter.next();
3787     if (bc != Bytecodes::_getfield)
3788       return false;
3789     bool ignore;
3790     value_field = iter.get_field(ignore);
3791     value_field_offset = value_field->offset_in_bytes();
3792   }
3793 
3794   // Null check without removing any arguments.
3795   _sp++;
3796   obj = do_null_check(obj, T_OBJECT);
3797   _sp--;
3798   // Check for locking null object
3799   if (stopped()) return true;
3800 
3801   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
3802   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
3803   int alias_idx = C->get_alias_index(adr_type);
3804 
3805   Node *result = _gvn.transform(new (C, 3) LoadLLockedNode(control(), memory(alias_idx), adr));
3806 
3807   push_pair(result);
3808 
3809   return true;
3810 }
3811 
3812 bool LibraryCallKit::inline_native_AtomicLong_attemptUpdate() {
3813   // Restore the stack and pop off the arguments
3814   _sp+=5;
3815   Node *newVal = pop_pair();
3816   Node *oldVal = pop_pair();
3817   Node *obj = pop();
3818 
3819   // we need the offset of the "value" field which was computed when
3820   // inlining the get() method.  Give up if we don't have it.
3821   if (value_field_offset == -1)
3822     return false;
3823 
3824   // Null check without removing any arguments.
3825   _sp+=5;
3826   obj = do_null_check(obj, T_OBJECT);
3827   _sp-=5;
3828   // Check for locking null object
3829   if (stopped()) return true;
3830 
3831   Node *adr = basic_plus_adr(obj, obj, value_field_offset);
3832   const TypePtr *adr_type = _gvn.type(adr)->is_ptr();
3833   int alias_idx = C->get_alias_index(adr_type);
3834 
3835   Node *cas = _gvn.transform(new (C, 5) StoreLConditionalNode(control(), memory(alias_idx), adr, newVal, oldVal));
3836   Node *store_proj = _gvn.transform( new (C, 1) SCMemProjNode(cas));
3837   set_memory(store_proj, alias_idx);
3838   Node *bol = _gvn.transform( new (C, 2) BoolNode( cas, BoolTest::eq ) );
3839 
3840   Node *result;
3841   // CMove node is not used to be able fold a possible check code
3842   // after attemptUpdate() call. This code could be transformed
3843   // into CMove node by loop optimizations.
3844   {
3845     RegionNode *r = new (C, 3) RegionNode(3);
3846     result = new (C, 3) PhiNode(r, TypeInt::BOOL);
3847 
3848     Node *iff = create_and_xform_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
3849     Node *iftrue = opt_iff(r, iff);
3850     r->init_req(1, iftrue);
3851     result->init_req(1, intcon(1));
3852     result->init_req(2, intcon(0));
3853 
3854     set_control(_gvn.transform(r));
3855     record_for_igvn(r);
3856 
3857     C->set_has_split_ifs(true); // Has chance for split-if optimization
3858   }
3859 
3860   push(_gvn.transform(result));
3861   return true;
3862 }
3863 
3864 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
3865   // restore the arguments
3866   _sp += arg_size();
3867 
3868   switch (id) {
3869   case vmIntrinsics::_floatToRawIntBits:
3870     push(_gvn.transform( new (C, 2) MoveF2INode(pop())));
3871     break;
3872 
3873   case vmIntrinsics::_intBitsToFloat:
3874     push(_gvn.transform( new (C, 2) MoveI2FNode(pop())));
3875     break;
3876 
3877   case vmIntrinsics::_doubleToRawLongBits:
3878     push_pair(_gvn.transform( new (C, 2) MoveD2LNode(pop_pair())));
3879     break;
3880 
3881   case vmIntrinsics::_longBitsToDouble:
3882     push_pair(_gvn.transform( new (C, 2) MoveL2DNode(pop_pair())));
3883     break;
3884 
3885   case vmIntrinsics::_doubleToLongBits: {
3886     Node* value = pop_pair();
3887 
3888     // two paths (plus control) merge in a wood
3889     RegionNode *r = new (C, 3) RegionNode(3);
3890     Node *phi = new (C, 3) PhiNode(r, TypeLong::LONG);
3891 
3892     Node *cmpisnan = _gvn.transform( new (C, 3) CmpDNode(value, value));
3893     // Build the boolean node
3894     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
3895 
3896     // Branch either way.
3897     // NaN case is less traveled, which makes all the difference.
3898     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3899     Node *opt_isnan = _gvn.transform(ifisnan);
3900     assert( opt_isnan->is_If(), "Expect an IfNode");
3901     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
3902     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
3903 
3904     set_control(iftrue);
3905 
3906     static const jlong nan_bits = CONST64(0x7ff8000000000000);
3907     Node *slow_result = longcon(nan_bits); // return NaN
3908     phi->init_req(1, _gvn.transform( slow_result ));
3909     r->init_req(1, iftrue);
3910 
3911     // Else fall through
3912     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
3913     set_control(iffalse);
3914 
3915     phi->init_req(2, _gvn.transform( new (C, 2) MoveD2LNode(value)));
3916     r->init_req(2, iffalse);
3917 
3918     // Post merge
3919     set_control(_gvn.transform(r));
3920     record_for_igvn(r);
3921 
3922     Node* result = _gvn.transform(phi);
3923     assert(result->bottom_type()->isa_long(), "must be");
3924     push_pair(result);
3925 
3926     C->set_has_split_ifs(true); // Has chance for split-if optimization
3927 
3928     break;
3929   }
3930 
3931   case vmIntrinsics::_floatToIntBits: {
3932     Node* value = pop();
3933 
3934     // two paths (plus control) merge in a wood
3935     RegionNode *r = new (C, 3) RegionNode(3);
3936     Node *phi = new (C, 3) PhiNode(r, TypeInt::INT);
3937 
3938     Node *cmpisnan = _gvn.transform( new (C, 3) CmpFNode(value, value));
3939     // Build the boolean node
3940     Node *bolisnan = _gvn.transform( new (C, 2) BoolNode( cmpisnan, BoolTest::ne ) );
3941 
3942     // Branch either way.
3943     // NaN case is less traveled, which makes all the difference.
3944     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3945     Node *opt_isnan = _gvn.transform(ifisnan);
3946     assert( opt_isnan->is_If(), "Expect an IfNode");
3947     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
3948     Node *iftrue = _gvn.transform( new (C, 1) IfTrueNode(opt_ifisnan) );
3949 
3950     set_control(iftrue);
3951 
3952     static const jint nan_bits = 0x7fc00000;
3953     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
3954     phi->init_req(1, _gvn.transform( slow_result ));
3955     r->init_req(1, iftrue);
3956 
3957     // Else fall through
3958     Node *iffalse = _gvn.transform( new (C, 1) IfFalseNode(opt_ifisnan) );
3959     set_control(iffalse);
3960 
3961     phi->init_req(2, _gvn.transform( new (C, 2) MoveF2INode(value)));
3962     r->init_req(2, iffalse);
3963 
3964     // Post merge
3965     set_control(_gvn.transform(r));
3966     record_for_igvn(r);
3967 
3968     Node* result = _gvn.transform(phi);
3969     assert(result->bottom_type()->isa_int(), "must be");
3970     push(result);
3971 
3972     C->set_has_split_ifs(true); // Has chance for split-if optimization
3973 
3974     break;
3975   }
3976 
3977   default:
3978     ShouldNotReachHere();
3979   }
3980 
3981   return true;
3982 }
3983 
3984 #ifdef _LP64
3985 #define XTOP ,top() /*additional argument*/
3986 #else  //_LP64
3987 #define XTOP        /*no additional argument*/
3988 #endif //_LP64
3989 
3990 //----------------------inline_unsafe_copyMemory-------------------------
3991 bool LibraryCallKit::inline_unsafe_copyMemory() {
3992   if (callee()->is_static())  return false;  // caller must have the capability!
3993   int nargs = 1 + 5 + 3;  // 5 args:  (src: ptr,off, dst: ptr,off, size)
3994   assert(signature()->size() == nargs-1, "copy has 5 arguments");
3995   null_check_receiver(callee());  // check then ignore argument(0)
3996   if (stopped())  return true;
3997 
3998   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3999 
4000   Node* src_ptr = argument(1);
4001   Node* src_off = ConvL2X(argument(2));
4002   assert(argument(3)->is_top(), "2nd half of long");
4003   Node* dst_ptr = argument(4);
4004   Node* dst_off = ConvL2X(argument(5));
4005   assert(argument(6)->is_top(), "2nd half of long");
4006   Node* size    = ConvL2X(argument(7));
4007   assert(argument(8)->is_top(), "2nd half of long");
4008 
4009   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
4010          "fieldOffset must be byte-scaled");
4011 
4012   Node* src = make_unsafe_address(src_ptr, src_off);
4013   Node* dst = make_unsafe_address(dst_ptr, dst_off);
4014 
4015   // Conservatively insert a memory barrier on all memory slices.
4016   // Do not let writes of the copy source or destination float below the copy.
4017   insert_mem_bar(Op_MemBarCPUOrder);
4018 
4019   // Call it.  Note that the length argument is not scaled.
4020   make_runtime_call(RC_LEAF|RC_NO_FP,
4021                     OptoRuntime::fast_arraycopy_Type(),
4022                     StubRoutines::unsafe_arraycopy(),
4023                     "unsafe_arraycopy",
4024                     TypeRawPtr::BOTTOM,
4025                     src, dst, size XTOP);
4026 
4027   // Do not let reads of the copy destination float above the copy.
4028   insert_mem_bar(Op_MemBarCPUOrder);
4029 
4030   return true;
4031 }
4032 
4033 //------------------------clone_coping-----------------------------------
4034 // Helper function for inline_native_clone.
4035 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark) {
4036   assert(obj_size != NULL, "");
4037   Node* raw_obj = alloc_obj->in(1);
4038   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4039 
4040   if (ReduceBulkZeroing) {
4041     // We will be completely responsible for initializing this object -
4042     // mark Initialize node as complete.
4043     AllocateNode* alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4044     // The object was just allocated - there should be no any stores!
4045     guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4046   }
4047 
4048   // Copy the fastest available way.
4049   // TODO: generate fields copies for small objects instead.
4050   Node* src  = obj;
4051   Node* dest = alloc_obj;
4052   Node* size = _gvn.transform(obj_size);
4053 
4054   // Exclude the header but include array length to copy by 8 bytes words.
4055   // Can't use base_offset_in_bytes(bt) since basic type is unknown.
4056   int base_off = is_array ? arrayOopDesc::length_offset_in_bytes() :
4057                             instanceOopDesc::base_offset_in_bytes();
4058   // base_off:
4059   // 8  - 32-bit VM
4060   // 12 - 64-bit VM, compressed oops
4061   // 16 - 64-bit VM, normal oops
4062   if (base_off % BytesPerLong != 0) {
4063     assert(UseCompressedOops, "");
4064     if (is_array) {
4065       // Exclude length to copy by 8 bytes words.
4066       base_off += sizeof(int);
4067     } else {
4068       // Include klass to copy by 8 bytes words.
4069       base_off = instanceOopDesc::klass_offset_in_bytes();
4070     }
4071     assert(base_off % BytesPerLong == 0, "expect 8 bytes alignment");
4072   }
4073   src  = basic_plus_adr(src,  base_off);
4074   dest = basic_plus_adr(dest, base_off);
4075 
4076   // Compute the length also, if needed:
4077   Node* countx = size;
4078   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(base_off)) );
4079   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong) ));
4080 
4081   const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4082   bool disjoint_bases = true;
4083   generate_unchecked_arraycopy(raw_adr_type, T_LONG, disjoint_bases,
4084                                src, NULL, dest, NULL, countx);
4085 
4086   // If necessary, emit some card marks afterwards.  (Non-arrays only.)
4087   if (card_mark) {
4088     assert(!is_array, "");
4089     // Put in store barrier for any and all oops we are sticking
4090     // into this object.  (We could avoid this if we could prove
4091     // that the object type contains no oop fields at all.)
4092     Node* no_particular_value = NULL;
4093     Node* no_particular_field = NULL;
4094     int raw_adr_idx = Compile::AliasIdxRaw;
4095     post_barrier(control(),
4096                  memory(raw_adr_type),
4097                  alloc_obj,
4098                  no_particular_field,
4099                  raw_adr_idx,
4100                  no_particular_value,
4101                  T_OBJECT,
4102                  false);
4103   }
4104 
4105   // Do not let reads from the cloned object float above the arraycopy.
4106   insert_mem_bar(Op_MemBarCPUOrder);
4107 }
4108 
4109 //------------------------inline_native_clone----------------------------
4110 // Here are the simple edge cases:
4111 //  null receiver => normal trap
4112 //  virtual and clone was overridden => slow path to out-of-line clone
4113 //  not cloneable or finalizer => slow path to out-of-line Object.clone
4114 //
4115 // The general case has two steps, allocation and copying.
4116 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4117 //
4118 // Copying also has two cases, oop arrays and everything else.
4119 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4120 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4121 //
4122 // These steps fold up nicely if and when the cloned object's klass
4123 // can be sharply typed as an object array, a type array, or an instance.
4124 //
4125 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4126   int nargs = 1;
4127   PhiNode* result_val;
4128 
4129   //set the original stack and the reexecute bit for the interpreter to reexecute
4130   //the bytecode that invokes Object.clone if deoptimization happens
4131   { PreserveReexecuteState preexecs(this);
4132     jvms()->set_should_reexecute(true);
4133 
4134     //null_check_receiver will adjust _sp (push and pop)
4135     Node* obj = null_check_receiver(callee());
4136     if (stopped())  return true;
4137 
4138     _sp += nargs;
4139 
4140     Node* obj_klass = load_object_klass(obj);
4141     const TypeKlassPtr* tklass = _gvn.type(obj_klass)->isa_klassptr();
4142     const TypeOopPtr*   toop   = ((tklass != NULL)
4143                                 ? tklass->as_instance_type()
4144                                 : TypeInstPtr::NOTNULL);
4145 
4146     // Conservatively insert a memory barrier on all memory slices.
4147     // Do not let writes into the original float below the clone.
4148     insert_mem_bar(Op_MemBarCPUOrder);
4149 
4150     // paths into result_reg:
4151     enum {
4152       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
4153       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
4154       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
4155       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
4156       PATH_LIMIT
4157     };
4158     RegionNode* result_reg = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
4159     result_val             = new(C, PATH_LIMIT) PhiNode(result_reg,
4160                                                         TypeInstPtr::NOTNULL);
4161     PhiNode*    result_i_o = new(C, PATH_LIMIT) PhiNode(result_reg, Type::ABIO);
4162     PhiNode*    result_mem = new(C, PATH_LIMIT) PhiNode(result_reg, Type::MEMORY,
4163                                                         TypePtr::BOTTOM);
4164     record_for_igvn(result_reg);
4165 
4166     const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM;
4167     int raw_adr_idx = Compile::AliasIdxRaw;
4168     const bool raw_mem_only = true;
4169 
4170 
4171     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4172     if (array_ctl != NULL) {
4173       // It's an array.
4174       PreserveJVMState pjvms(this);
4175       set_control(array_ctl);
4176       Node* obj_length = load_array_length(obj);
4177       Node* obj_size  = NULL;
4178       Node* alloc_obj = new_array(obj_klass, obj_length, 0,
4179                                   raw_mem_only, &obj_size);
4180 
4181       if (!use_ReduceInitialCardMarks()) {
4182         // If it is an oop array, it requires very special treatment,
4183         // because card marking is required on each card of the array.
4184         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4185         if (is_obja != NULL) {
4186           PreserveJVMState pjvms2(this);
4187           set_control(is_obja);
4188           // Generate a direct call to the right arraycopy function(s).
4189           bool disjoint_bases = true;
4190           bool length_never_negative = true;
4191           generate_arraycopy(TypeAryPtr::OOPS, T_OBJECT,
4192                              obj, intcon(0), alloc_obj, intcon(0),
4193                              obj_length,
4194                              disjoint_bases, length_never_negative);
4195           result_reg->init_req(_objArray_path, control());
4196           result_val->init_req(_objArray_path, alloc_obj);
4197           result_i_o ->set_req(_objArray_path, i_o());
4198           result_mem ->set_req(_objArray_path, reset_memory());
4199         }
4200       }
4201       // Otherwise, there are no card marks to worry about.
4202       // (We can dispense with card marks if we know the allocation
4203       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
4204       //  causes the non-eden paths to take compensating steps to
4205       //  simulate a fresh allocation, so that no further
4206       //  card marks are required in compiled code to initialize
4207       //  the object.)
4208 
4209       if (!stopped()) {
4210         copy_to_clone(obj, alloc_obj, obj_size, true, false);
4211 
4212         // Present the results of the copy.
4213         result_reg->init_req(_array_path, control());
4214         result_val->init_req(_array_path, alloc_obj);
4215         result_i_o ->set_req(_array_path, i_o());
4216         result_mem ->set_req(_array_path, reset_memory());
4217       }
4218     }
4219 
4220     // We only go to the instance fast case code if we pass a number of guards.
4221     // The paths which do not pass are accumulated in the slow_region.
4222     RegionNode* slow_region = new (C, 1) RegionNode(1);
4223     record_for_igvn(slow_region);
4224     if (!stopped()) {
4225       // It's an instance (we did array above).  Make the slow-path tests.
4226       // If this is a virtual call, we generate a funny guard.  We grab
4227       // the vtable entry corresponding to clone() from the target object.
4228       // If the target method which we are calling happens to be the
4229       // Object clone() method, we pass the guard.  We do not need this
4230       // guard for non-virtual calls; the caller is known to be the native
4231       // Object clone().
4232       if (is_virtual) {
4233         generate_virtual_guard(obj_klass, slow_region);
4234       }
4235 
4236       // The object must be cloneable and must not have a finalizer.
4237       // Both of these conditions may be checked in a single test.
4238       // We could optimize the cloneable test further, but we don't care.
4239       generate_access_flags_guard(obj_klass,
4240                                   // Test both conditions:
4241                                   JVM_ACC_IS_CLONEABLE | JVM_ACC_HAS_FINALIZER,
4242                                   // Must be cloneable but not finalizer:
4243                                   JVM_ACC_IS_CLONEABLE,
4244                                   slow_region);
4245     }
4246 
4247     if (!stopped()) {
4248       // It's an instance, and it passed the slow-path tests.
4249       PreserveJVMState pjvms(this);
4250       Node* obj_size  = NULL;
4251       Node* alloc_obj = new_instance(obj_klass, NULL, raw_mem_only, &obj_size);
4252 
4253       copy_to_clone(obj, alloc_obj, obj_size, false, !use_ReduceInitialCardMarks());
4254 
4255       // Present the results of the slow call.
4256       result_reg->init_req(_instance_path, control());
4257       result_val->init_req(_instance_path, alloc_obj);
4258       result_i_o ->set_req(_instance_path, i_o());
4259       result_mem ->set_req(_instance_path, reset_memory());
4260     }
4261 
4262     // Generate code for the slow case.  We make a call to clone().
4263     set_control(_gvn.transform(slow_region));
4264     if (!stopped()) {
4265       PreserveJVMState pjvms(this);
4266       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4267       Node* slow_result = set_results_for_java_call(slow_call);
4268       // this->control() comes from set_results_for_java_call
4269       result_reg->init_req(_slow_path, control());
4270       result_val->init_req(_slow_path, slow_result);
4271       result_i_o ->set_req(_slow_path, i_o());
4272       result_mem ->set_req(_slow_path, reset_memory());
4273     }
4274 
4275     // Return the combined state.
4276     set_control(    _gvn.transform(result_reg) );
4277     set_i_o(        _gvn.transform(result_i_o) );
4278     set_all_memory( _gvn.transform(result_mem) );
4279   } //original reexecute and sp are set back here
4280 
4281   push(_gvn.transform(result_val));
4282 
4283   return true;
4284 }
4285 
4286 
4287 // constants for computing the copy function
4288 enum {
4289   COPYFUNC_UNALIGNED = 0,
4290   COPYFUNC_ALIGNED = 1,                 // src, dest aligned to HeapWordSize
4291   COPYFUNC_CONJOINT = 0,
4292   COPYFUNC_DISJOINT = 2                 // src != dest, or transfer can descend
4293 };
4294 
4295 // Note:  The condition "disjoint" applies also for overlapping copies
4296 // where an descending copy is permitted (i.e., dest_offset <= src_offset).
4297 static address
4298 select_arraycopy_function(BasicType t, bool aligned, bool disjoint, const char* &name, bool need_pre_barrier) {
4299   int selector =
4300     (aligned  ? COPYFUNC_ALIGNED  : COPYFUNC_UNALIGNED) +
4301     (disjoint ? COPYFUNC_DISJOINT : COPYFUNC_CONJOINT);
4302 
4303 #define RETURN_STUB(xxx_arraycopy) { \
4304   name = #xxx_arraycopy; \
4305   return StubRoutines::xxx_arraycopy(); }
4306 
4307 #define RETURN_STUB_PARM(xxx_arraycopy, parm) {           \
4308   name = #xxx_arraycopy; \
4309   return StubRoutines::xxx_arraycopy(parm); }
4310 
4311   switch (t) {
4312   case T_BYTE:
4313   case T_BOOLEAN:
4314     switch (selector) {
4315     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_arraycopy);
4316     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_arraycopy);
4317     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jbyte_disjoint_arraycopy);
4318     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jbyte_disjoint_arraycopy);
4319     }
4320   case T_CHAR:
4321   case T_SHORT:
4322     switch (selector) {
4323     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_arraycopy);
4324     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_arraycopy);
4325     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jshort_disjoint_arraycopy);
4326     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jshort_disjoint_arraycopy);
4327     }
4328   case T_INT:
4329   case T_FLOAT:
4330     switch (selector) {
4331     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_arraycopy);
4332     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_arraycopy);
4333     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jint_disjoint_arraycopy);
4334     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jint_disjoint_arraycopy);
4335     }
4336   case T_DOUBLE:
4337   case T_LONG:
4338     switch (selector) {
4339     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_arraycopy);
4340     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_arraycopy);
4341     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB(jlong_disjoint_arraycopy);
4342     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB(arrayof_jlong_disjoint_arraycopy);
4343     }
4344   case T_ARRAY:
4345   case T_OBJECT:
4346     switch (selector) {
4347     case COPYFUNC_CONJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB_PARM(oop_arraycopy, need_pre_barrier);
4348     case COPYFUNC_CONJOINT | COPYFUNC_ALIGNED:    RETURN_STUB_PARM(arrayof_oop_arraycopy, need_pre_barrier);
4349     case COPYFUNC_DISJOINT | COPYFUNC_UNALIGNED:  RETURN_STUB_PARM(oop_disjoint_arraycopy, need_pre_barrier);
4350     case COPYFUNC_DISJOINT | COPYFUNC_ALIGNED:    RETURN_STUB_PARM(arrayof_oop_disjoint_arraycopy, need_pre_barrier);
4351     }
4352   default:
4353     ShouldNotReachHere();
4354     return NULL;
4355   }
4356 
4357 #undef RETURN_STUB
4358 #undef RETURN_STUB_PARM
4359 }
4360 
4361 //------------------------------basictype2arraycopy----------------------------
4362 address LibraryCallKit::basictype2arraycopy(BasicType t,
4363                                             Node* src_offset,
4364                                             Node* dest_offset,
4365                                             bool disjoint_bases,
4366                                             const char* &name,
4367                                             bool need_pre_barrier) {
4368   const TypeInt* src_offset_inttype  = gvn().find_int_type(src_offset);;
4369   const TypeInt* dest_offset_inttype = gvn().find_int_type(dest_offset);;
4370 
4371   bool aligned = false;
4372   bool disjoint = disjoint_bases;
4373 
4374   // if the offsets are the same, we can treat the memory regions as
4375   // disjoint, because either the memory regions are in different arrays,
4376   // or they are identical (which we can treat as disjoint.)  We can also
4377   // treat a copy with a destination index  less that the source index
4378   // as disjoint since a low->high copy will work correctly in this case.
4379   if (src_offset_inttype != NULL && src_offset_inttype->is_con() &&
4380       dest_offset_inttype != NULL && dest_offset_inttype->is_con()) {
4381     // both indices are constants
4382     int s_offs = src_offset_inttype->get_con();
4383     int d_offs = dest_offset_inttype->get_con();
4384     int element_size = type2aelembytes(t);
4385     aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) &&
4386               ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0);
4387     if (s_offs >= d_offs)  disjoint = true;
4388   } else if (src_offset == dest_offset && src_offset != NULL) {
4389     // This can occur if the offsets are identical non-constants.
4390     disjoint = true;
4391   }
4392 
4393   return select_arraycopy_function(t, aligned, disjoint, name, need_pre_barrier);
4394 }
4395 
4396 
4397 //------------------------------inline_arraycopy-----------------------
4398 bool LibraryCallKit::inline_arraycopy() {
4399   // Restore the stack and pop off the arguments.
4400   int nargs = 5;  // 2 oops, 3 ints, no size_t or long
4401   assert(callee()->signature()->size() == nargs, "copy has 5 arguments");
4402 
4403   Node *src         = argument(0);
4404   Node *src_offset  = argument(1);
4405   Node *dest        = argument(2);
4406   Node *dest_offset = argument(3);
4407   Node *length      = argument(4);
4408 
4409   // Compile time checks.  If any of these checks cannot be verified at compile time,
4410   // we do not make a fast path for this call.  Instead, we let the call remain as it
4411   // is.  The checks we choose to mandate at compile time are:
4412   //
4413   // (1) src and dest are arrays.
4414   const Type* src_type = src->Value(&_gvn);
4415   const Type* dest_type = dest->Value(&_gvn);
4416   const TypeAryPtr* top_src = src_type->isa_aryptr();
4417   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4418   if (top_src  == NULL || top_src->klass()  == NULL ||
4419       top_dest == NULL || top_dest->klass() == NULL) {
4420     // Conservatively insert a memory barrier on all memory slices.
4421     // Do not let writes into the source float below the arraycopy.
4422     insert_mem_bar(Op_MemBarCPUOrder);
4423 
4424     // Call StubRoutines::generic_arraycopy stub.
4425     generate_arraycopy(TypeRawPtr::BOTTOM, T_CONFLICT,
4426                        src, src_offset, dest, dest_offset, length);
4427 
4428     // Do not let reads from the destination float above the arraycopy.
4429     // Since we cannot type the arrays, we don't know which slices
4430     // might be affected.  We could restrict this barrier only to those
4431     // memory slices which pertain to array elements--but don't bother.
4432     if (!InsertMemBarAfterArraycopy)
4433       // (If InsertMemBarAfterArraycopy, there is already one in place.)
4434       insert_mem_bar(Op_MemBarCPUOrder);
4435     return true;
4436   }
4437 
4438   // (2) src and dest arrays must have elements of the same BasicType
4439   // Figure out the size and type of the elements we will be copying.
4440   BasicType src_elem  =  top_src->klass()->as_array_klass()->element_type()->basic_type();
4441   BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
4442   if (src_elem  == T_ARRAY)  src_elem  = T_OBJECT;
4443   if (dest_elem == T_ARRAY)  dest_elem = T_OBJECT;
4444 
4445   if (src_elem != dest_elem || dest_elem == T_VOID) {
4446     // The component types are not the same or are not recognized.  Punt.
4447     // (But, avoid the native method wrapper to JVM_ArrayCopy.)
4448     generate_slow_arraycopy(TypePtr::BOTTOM,
4449                             src, src_offset, dest, dest_offset, length);
4450     return true;
4451   }
4452 
4453   //---------------------------------------------------------------------------
4454   // We will make a fast path for this call to arraycopy.
4455 
4456   // We have the following tests left to perform:
4457   //
4458   // (3) src and dest must not be null.
4459   // (4) src_offset must not be negative.
4460   // (5) dest_offset must not be negative.
4461   // (6) length must not be negative.
4462   // (7) src_offset + length must not exceed length of src.
4463   // (8) dest_offset + length must not exceed length of dest.
4464   // (9) each element of an oop array must be assignable
4465 
4466   RegionNode* slow_region = new (C, 1) RegionNode(1);
4467   record_for_igvn(slow_region);
4468 
4469   // (3) operands must not be null
4470   // We currently perform our null checks with the do_null_check routine.
4471   // This means that the null exceptions will be reported in the caller
4472   // rather than (correctly) reported inside of the native arraycopy call.
4473   // This should be corrected, given time.  We do our null check with the
4474   // stack pointer restored.
4475   _sp += nargs;
4476   src  = do_null_check(src,  T_ARRAY);
4477   dest = do_null_check(dest, T_ARRAY);
4478   _sp -= nargs;
4479 
4480   // (4) src_offset must not be negative.
4481   generate_negative_guard(src_offset, slow_region);
4482 
4483   // (5) dest_offset must not be negative.
4484   generate_negative_guard(dest_offset, slow_region);
4485 
4486   // (6) length must not be negative (moved to generate_arraycopy()).
4487   // generate_negative_guard(length, slow_region);
4488 
4489   // (7) src_offset + length must not exceed length of src.
4490   generate_limit_guard(src_offset, length,
4491                        load_array_length(src),
4492                        slow_region);
4493 
4494   // (8) dest_offset + length must not exceed length of dest.
4495   generate_limit_guard(dest_offset, length,
4496                        load_array_length(dest),
4497                        slow_region);
4498 
4499   // (9) each element of an oop array must be assignable
4500   // The generate_arraycopy subroutine checks this.
4501 
4502   // This is where the memory effects are placed:
4503   const TypePtr* adr_type = TypeAryPtr::get_array_body_type(dest_elem);
4504   generate_arraycopy(adr_type, dest_elem,
4505                      src, src_offset, dest, dest_offset, length,
4506                      false, false, slow_region);
4507 
4508   return true;
4509 }
4510 
4511 //-----------------------------generate_arraycopy----------------------
4512 // Generate an optimized call to arraycopy.
4513 // Caller must guard against non-arrays.
4514 // Caller must determine a common array basic-type for both arrays.
4515 // Caller must validate offsets against array bounds.
4516 // The slow_region has already collected guard failure paths
4517 // (such as out of bounds length or non-conformable array types).
4518 // The generated code has this shape, in general:
4519 //
4520 //     if (length == 0)  return   // via zero_path
4521 //     slowval = -1
4522 //     if (types unknown) {
4523 //       slowval = call generic copy loop
4524 //       if (slowval == 0)  return  // via checked_path
4525 //     } else if (indexes in bounds) {
4526 //       if ((is object array) && !(array type check)) {
4527 //         slowval = call checked copy loop
4528 //         if (slowval == 0)  return  // via checked_path
4529 //       } else {
4530 //         call bulk copy loop
4531 //         return  // via fast_path
4532 //       }
4533 //     }
4534 //     // adjust params for remaining work:
4535 //     if (slowval != -1) {
4536 //       n = -1^slowval; src_offset += n; dest_offset += n; length -= n
4537 //     }
4538 //   slow_region:
4539 //     call slow arraycopy(src, src_offset, dest, dest_offset, length)
4540 //     return  // via slow_call_path
4541 //
4542 // This routine is used from several intrinsics:  System.arraycopy,
4543 // Object.clone (the array subcase), and Arrays.copyOf[Range].
4544 //
4545 void
4546 LibraryCallKit::generate_arraycopy(const TypePtr* adr_type,
4547                                    BasicType basic_elem_type,
4548                                    Node* src,  Node* src_offset,
4549                                    Node* dest, Node* dest_offset,
4550                                    Node* copy_length,
4551                                    bool disjoint_bases,
4552                                    bool length_never_negative,
4553                                    RegionNode* slow_region) {
4554 
4555   if (slow_region == NULL) {
4556     slow_region = new(C,1) RegionNode(1);
4557     record_for_igvn(slow_region);
4558   }
4559 
4560   Node* original_dest      = dest;
4561   AllocateArrayNode* alloc = NULL;  // used for zeroing, if needed
4562   bool  must_clear_dest    = false;
4563 
4564   // See if this is the initialization of a newly-allocated array.
4565   // If so, we will take responsibility here for initializing it to zero.
4566   // (Note:  Because tightly_coupled_allocation performs checks on the
4567   // out-edges of the dest, we need to avoid making derived pointers
4568   // from it until we have checked its uses.)
4569   if (ReduceBulkZeroing
4570       && !ZeroTLAB              // pointless if already zeroed
4571       && basic_elem_type != T_CONFLICT // avoid corner case
4572       && !_gvn.eqv_uncast(src, dest)
4573       && ((alloc = tightly_coupled_allocation(dest, slow_region))
4574           != NULL)
4575       && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0
4576       && alloc->maybe_set_complete(&_gvn)) {
4577     // "You break it, you buy it."
4578     InitializeNode* init = alloc->initialization();
4579     assert(init->is_complete(), "we just did this");
4580     assert(dest->is_CheckCastPP(), "sanity");
4581     assert(dest->in(0)->in(0) == init, "dest pinned");
4582     adr_type = TypeRawPtr::BOTTOM;  // all initializations are into raw memory
4583     // From this point on, every exit path is responsible for
4584     // initializing any non-copied parts of the object to zero.
4585     must_clear_dest = true;
4586   } else {
4587     // No zeroing elimination here.
4588     alloc             = NULL;
4589     //original_dest   = dest;
4590     //must_clear_dest = false;
4591   }
4592 
4593   // Results are placed here:
4594   enum { fast_path        = 1,  // normal void-returning assembly stub
4595          checked_path     = 2,  // special assembly stub with cleanup
4596          slow_call_path   = 3,  // something went wrong; call the VM
4597          zero_path        = 4,  // bypass when length of copy is zero
4598          bcopy_path       = 5,  // copy primitive array by 64-bit blocks
4599          PATH_LIMIT       = 6
4600   };
4601   RegionNode* result_region = new(C, PATH_LIMIT) RegionNode(PATH_LIMIT);
4602   PhiNode*    result_i_o    = new(C, PATH_LIMIT) PhiNode(result_region, Type::ABIO);
4603   PhiNode*    result_memory = new(C, PATH_LIMIT) PhiNode(result_region, Type::MEMORY, adr_type);
4604   record_for_igvn(result_region);
4605   _gvn.set_type_bottom(result_i_o);
4606   _gvn.set_type_bottom(result_memory);
4607   assert(adr_type != TypePtr::BOTTOM, "must be RawMem or a T[] slice");
4608 
4609   // The slow_control path:
4610   Node* slow_control;
4611   Node* slow_i_o = i_o();
4612   Node* slow_mem = memory(adr_type);
4613   debug_only(slow_control = (Node*) badAddress);
4614 
4615   // Checked control path:
4616   Node* checked_control = top();
4617   Node* checked_mem     = NULL;
4618   Node* checked_i_o     = NULL;
4619   Node* checked_value   = NULL;
4620 
4621   if (basic_elem_type == T_CONFLICT) {
4622     assert(!must_clear_dest, "");
4623     Node* cv = generate_generic_arraycopy(adr_type,
4624                                           src, src_offset, dest, dest_offset,
4625                                           copy_length);
4626     if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
4627     checked_control = control();
4628     checked_i_o     = i_o();
4629     checked_mem     = memory(adr_type);
4630     checked_value   = cv;
4631     set_control(top());         // no fast path
4632   }
4633 
4634   Node* not_pos = generate_nonpositive_guard(copy_length, length_never_negative);
4635   if (not_pos != NULL) {
4636     PreserveJVMState pjvms(this);
4637     set_control(not_pos);
4638 
4639     // (6) length must not be negative.
4640     if (!length_never_negative) {
4641       generate_negative_guard(copy_length, slow_region);
4642     }
4643 
4644     // copy_length is 0.
4645     if (!stopped() && must_clear_dest) {
4646       Node* dest_length = alloc->in(AllocateNode::ALength);
4647       if (_gvn.eqv_uncast(copy_length, dest_length)
4648           || _gvn.find_int_con(dest_length, 1) <= 0) {
4649         // There is no zeroing to do. No need for a secondary raw memory barrier.
4650       } else {
4651         // Clear the whole thing since there are no source elements to copy.
4652         generate_clear_array(adr_type, dest, basic_elem_type,
4653                              intcon(0), NULL,
4654                              alloc->in(AllocateNode::AllocSize));
4655         // Use a secondary InitializeNode as raw memory barrier.
4656         // Currently it is needed only on this path since other
4657         // paths have stub or runtime calls as raw memory barriers.
4658         InitializeNode* init = insert_mem_bar_volatile(Op_Initialize,
4659                                                        Compile::AliasIdxRaw,
4660                                                        top())->as_Initialize();
4661         init->set_complete(&_gvn);  // (there is no corresponding AllocateNode)
4662       }
4663     }
4664 
4665     // Present the results of the fast call.
4666     result_region->init_req(zero_path, control());
4667     result_i_o   ->init_req(zero_path, i_o());
4668     result_memory->init_req(zero_path, memory(adr_type));
4669   }
4670 
4671   if (!stopped() && must_clear_dest) {
4672     // We have to initialize the *uncopied* part of the array to zero.
4673     // The copy destination is the slice dest[off..off+len].  The other slices
4674     // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length].
4675     Node* dest_size   = alloc->in(AllocateNode::AllocSize);
4676     Node* dest_length = alloc->in(AllocateNode::ALength);
4677     Node* dest_tail   = _gvn.transform( new(C,3) AddINode(dest_offset,
4678                                                           copy_length) );
4679 
4680     // If there is a head section that needs zeroing, do it now.
4681     if (find_int_con(dest_offset, -1) != 0) {
4682       generate_clear_array(adr_type, dest, basic_elem_type,
4683                            intcon(0), dest_offset,
4684                            NULL);
4685     }
4686 
4687     // Next, perform a dynamic check on the tail length.
4688     // It is often zero, and we can win big if we prove this.
4689     // There are two wins:  Avoid generating the ClearArray
4690     // with its attendant messy index arithmetic, and upgrade
4691     // the copy to a more hardware-friendly word size of 64 bits.
4692     Node* tail_ctl = NULL;
4693     if (!stopped() && !_gvn.eqv_uncast(dest_tail, dest_length)) {
4694       Node* cmp_lt   = _gvn.transform( new(C,3) CmpINode(dest_tail, dest_length) );
4695       Node* bol_lt   = _gvn.transform( new(C,2) BoolNode(cmp_lt, BoolTest::lt) );
4696       tail_ctl = generate_slow_guard(bol_lt, NULL);
4697       assert(tail_ctl != NULL || !stopped(), "must be an outcome");
4698     }
4699 
4700     // At this point, let's assume there is no tail.
4701     if (!stopped() && alloc != NULL && basic_elem_type != T_OBJECT) {
4702       // There is no tail.  Try an upgrade to a 64-bit copy.
4703       bool didit = false;
4704       { PreserveJVMState pjvms(this);
4705         didit = generate_block_arraycopy(adr_type, basic_elem_type, alloc,
4706                                          src, src_offset, dest, dest_offset,
4707                                          dest_size);
4708         if (didit) {
4709           // Present the results of the block-copying fast call.
4710           result_region->init_req(bcopy_path, control());
4711           result_i_o   ->init_req(bcopy_path, i_o());
4712           result_memory->init_req(bcopy_path, memory(adr_type));
4713         }
4714       }
4715       if (didit)
4716         set_control(top());     // no regular fast path
4717     }
4718 
4719     // Clear the tail, if any.
4720     if (tail_ctl != NULL) {
4721       Node* notail_ctl = stopped() ? NULL : control();
4722       set_control(tail_ctl);
4723       if (notail_ctl == NULL) {
4724         generate_clear_array(adr_type, dest, basic_elem_type,
4725                              dest_tail, NULL,
4726                              dest_size);
4727       } else {
4728         // Make a local merge.
4729         Node* done_ctl = new(C,3) RegionNode(3);
4730         Node* done_mem = new(C,3) PhiNode(done_ctl, Type::MEMORY, adr_type);
4731         done_ctl->init_req(1, notail_ctl);
4732         done_mem->init_req(1, memory(adr_type));
4733         generate_clear_array(adr_type, dest, basic_elem_type,
4734                              dest_tail, NULL,
4735                              dest_size);
4736         done_ctl->init_req(2, control());
4737         done_mem->init_req(2, memory(adr_type));
4738         set_control( _gvn.transform(done_ctl) );
4739         set_memory(  _gvn.transform(done_mem), adr_type );
4740       }
4741     }
4742   }
4743 
4744   BasicType copy_type = basic_elem_type;
4745   assert(basic_elem_type != T_ARRAY, "caller must fix this");
4746   if (!stopped() && copy_type == T_OBJECT) {
4747     // If src and dest have compatible element types, we can copy bits.
4748     // Types S[] and D[] are compatible if D is a supertype of S.
4749     //
4750     // If they are not, we will use checked_oop_disjoint_arraycopy,
4751     // which performs a fast optimistic per-oop check, and backs off
4752     // further to JVM_ArrayCopy on the first per-oop check that fails.
4753     // (Actually, we don't move raw bits only; the GC requires card marks.)
4754 
4755     // Get the klassOop for both src and dest
4756     Node* src_klass  = load_object_klass(src);
4757     Node* dest_klass = load_object_klass(dest);
4758 
4759     // Generate the subtype check.
4760     // This might fold up statically, or then again it might not.
4761     //
4762     // Non-static example:  Copying List<String>.elements to a new String[].
4763     // The backing store for a List<String> is always an Object[],
4764     // but its elements are always type String, if the generic types
4765     // are correct at the source level.
4766     //
4767     // Test S[] against D[], not S against D, because (probably)
4768     // the secondary supertype cache is less busy for S[] than S.
4769     // This usually only matters when D is an interface.
4770     Node* not_subtype_ctrl = gen_subtype_check(src_klass, dest_klass);
4771     // Plug failing path into checked_oop_disjoint_arraycopy
4772     if (not_subtype_ctrl != top()) {
4773       PreserveJVMState pjvms(this);
4774       set_control(not_subtype_ctrl);
4775       // (At this point we can assume disjoint_bases, since types differ.)
4776       int ek_offset = objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc);
4777       Node* p1 = basic_plus_adr(dest_klass, ek_offset);
4778       Node* n1 = LoadKlassNode::make(_gvn, immutable_memory(), p1, TypeRawPtr::BOTTOM);
4779       Node* dest_elem_klass = _gvn.transform(n1);
4780       Node* cv = generate_checkcast_arraycopy(adr_type,
4781                                               dest_elem_klass,
4782                                               src, src_offset, dest, dest_offset,
4783                                               ConvI2X(copy_length), !must_clear_dest);
4784       if (cv == NULL)  cv = intcon(-1);  // failure (no stub available)
4785       checked_control = control();
4786       checked_i_o     = i_o();
4787       checked_mem     = memory(adr_type);
4788       checked_value   = cv;
4789     }
4790     // At this point we know we do not need type checks on oop stores.
4791 
4792     // Let's see if we need card marks:
4793     if (alloc != NULL && use_ReduceInitialCardMarks()) {
4794       // If we do not need card marks, copy using the jint or jlong stub.
4795       copy_type = LP64_ONLY(UseCompressedOops ? T_INT : T_LONG) NOT_LP64(T_INT);
4796       assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type),
4797              "sizes agree");
4798     }
4799   }
4800 
4801   if (!stopped()) {
4802     // Generate the fast path, if possible.
4803     PreserveJVMState pjvms(this);
4804     generate_unchecked_arraycopy(adr_type, copy_type, disjoint_bases,
4805                                  src, src_offset, dest, dest_offset,
4806                                  ConvI2X(copy_length), !must_clear_dest);
4807 
4808     // Present the results of the fast call.
4809     result_region->init_req(fast_path, control());
4810     result_i_o   ->init_req(fast_path, i_o());
4811     result_memory->init_req(fast_path, memory(adr_type));
4812   }
4813 
4814   // Here are all the slow paths up to this point, in one bundle:
4815   slow_control = top();
4816   if (slow_region != NULL)
4817     slow_control = _gvn.transform(slow_region);
4818   debug_only(slow_region = (RegionNode*)badAddress);
4819 
4820   set_control(checked_control);
4821   if (!stopped()) {
4822     // Clean up after the checked call.
4823     // The returned value is either 0 or -1^K,
4824     // where K = number of partially transferred array elements.
4825     Node* cmp = _gvn.transform( new(C, 3) CmpINode(checked_value, intcon(0)) );
4826     Node* bol = _gvn.transform( new(C, 2) BoolNode(cmp, BoolTest::eq) );
4827     IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
4828 
4829     // If it is 0, we are done, so transfer to the end.
4830     Node* checks_done = _gvn.transform( new(C, 1) IfTrueNode(iff) );
4831     result_region->init_req(checked_path, checks_done);
4832     result_i_o   ->init_req(checked_path, checked_i_o);
4833     result_memory->init_req(checked_path, checked_mem);
4834 
4835     // If it is not zero, merge into the slow call.
4836     set_control( _gvn.transform( new(C, 1) IfFalseNode(iff) ));
4837     RegionNode* slow_reg2 = new(C, 3) RegionNode(3);
4838     PhiNode*    slow_i_o2 = new(C, 3) PhiNode(slow_reg2, Type::ABIO);
4839     PhiNode*    slow_mem2 = new(C, 3) PhiNode(slow_reg2, Type::MEMORY, adr_type);
4840     record_for_igvn(slow_reg2);
4841     slow_reg2  ->init_req(1, slow_control);
4842     slow_i_o2  ->init_req(1, slow_i_o);
4843     slow_mem2  ->init_req(1, slow_mem);
4844     slow_reg2  ->init_req(2, control());
4845     slow_i_o2  ->init_req(2, checked_i_o);
4846     slow_mem2  ->init_req(2, checked_mem);
4847 
4848     slow_control = _gvn.transform(slow_reg2);
4849     slow_i_o     = _gvn.transform(slow_i_o2);
4850     slow_mem     = _gvn.transform(slow_mem2);
4851 
4852     if (alloc != NULL) {
4853       // We'll restart from the very beginning, after zeroing the whole thing.
4854       // This can cause double writes, but that's OK since dest is brand new.
4855       // So we ignore the low 31 bits of the value returned from the stub.
4856     } else {
4857       // We must continue the copy exactly where it failed, or else
4858       // another thread might see the wrong number of writes to dest.
4859       Node* checked_offset = _gvn.transform( new(C, 3) XorINode(checked_value, intcon(-1)) );
4860       Node* slow_offset    = new(C, 3) PhiNode(slow_reg2, TypeInt::INT);
4861       slow_offset->init_req(1, intcon(0));
4862       slow_offset->init_req(2, checked_offset);
4863       slow_offset  = _gvn.transform(slow_offset);
4864 
4865       // Adjust the arguments by the conditionally incoming offset.
4866       Node* src_off_plus  = _gvn.transform( new(C, 3) AddINode(src_offset,  slow_offset) );
4867       Node* dest_off_plus = _gvn.transform( new(C, 3) AddINode(dest_offset, slow_offset) );
4868       Node* length_minus  = _gvn.transform( new(C, 3) SubINode(copy_length, slow_offset) );
4869 
4870       // Tweak the node variables to adjust the code produced below:
4871       src_offset  = src_off_plus;
4872       dest_offset = dest_off_plus;
4873       copy_length = length_minus;
4874     }
4875   }
4876 
4877   set_control(slow_control);
4878   if (!stopped()) {
4879     // Generate the slow path, if needed.
4880     PreserveJVMState pjvms(this);   // replace_in_map may trash the map
4881 
4882     set_memory(slow_mem, adr_type);
4883     set_i_o(slow_i_o);
4884 
4885     if (must_clear_dest) {
4886       generate_clear_array(adr_type, dest, basic_elem_type,
4887                            intcon(0), NULL,
4888                            alloc->in(AllocateNode::AllocSize));
4889     }
4890 
4891     generate_slow_arraycopy(adr_type,
4892                             src, src_offset, dest, dest_offset,
4893                             copy_length);
4894 
4895     result_region->init_req(slow_call_path, control());
4896     result_i_o   ->init_req(slow_call_path, i_o());
4897     result_memory->init_req(slow_call_path, memory(adr_type));
4898   }
4899 
4900   // Remove unused edges.
4901   for (uint i = 1; i < result_region->req(); i++) {
4902     if (result_region->in(i) == NULL)
4903       result_region->init_req(i, top());
4904   }
4905 
4906   // Finished; return the combined state.
4907   set_control( _gvn.transform(result_region) );
4908   set_i_o(     _gvn.transform(result_i_o)    );
4909   set_memory(  _gvn.transform(result_memory), adr_type );
4910 
4911   // The memory edges above are precise in order to model effects around
4912   // array copies accurately to allow value numbering of field loads around
4913   // arraycopy.  Such field loads, both before and after, are common in Java
4914   // collections and similar classes involving header/array data structures.
4915   //
4916   // But with low number of register or when some registers are used or killed
4917   // by arraycopy calls it causes registers spilling on stack. See 6544710.
4918   // The next memory barrier is added to avoid it. If the arraycopy can be
4919   // optimized away (which it can, sometimes) then we can manually remove
4920   // the membar also.
4921   //
4922   // Do not let reads from the cloned object float above the arraycopy.
4923   if (InsertMemBarAfterArraycopy || alloc != NULL)
4924     insert_mem_bar(Op_MemBarCPUOrder);
4925 }
4926 
4927 
4928 // Helper function which determines if an arraycopy immediately follows
4929 // an allocation, with no intervening tests or other escapes for the object.
4930 AllocateArrayNode*
4931 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
4932                                            RegionNode* slow_region) {
4933   if (stopped())             return NULL;  // no fast path
4934   if (C->AliasLevel() == 0)  return NULL;  // no MergeMems around
4935 
4936   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
4937   if (alloc == NULL)  return NULL;
4938 
4939   Node* rawmem = memory(Compile::AliasIdxRaw);
4940   // Is the allocation's memory state untouched?
4941   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
4942     // Bail out if there have been raw-memory effects since the allocation.
4943     // (Example:  There might have been a call or safepoint.)
4944     return NULL;
4945   }
4946   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
4947   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
4948     return NULL;
4949   }
4950 
4951   // There must be no unexpected observers of this allocation.
4952   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
4953     Node* obs = ptr->fast_out(i);
4954     if (obs != this->map()) {
4955       return NULL;
4956     }
4957   }
4958 
4959   // This arraycopy must unconditionally follow the allocation of the ptr.
4960   Node* alloc_ctl = ptr->in(0);
4961   assert(just_allocated_object(alloc_ctl) == ptr, "most recent allo");
4962 
4963   Node* ctl = control();
4964   while (ctl != alloc_ctl) {
4965     // There may be guards which feed into the slow_region.
4966     // Any other control flow means that we might not get a chance
4967     // to finish initializing the allocated object.
4968     if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
4969       IfNode* iff = ctl->in(0)->as_If();
4970       Node* not_ctl = iff->proj_out(1 - ctl->as_Proj()->_con);
4971       assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
4972       if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
4973         ctl = iff->in(0);       // This test feeds the known slow_region.
4974         continue;
4975       }
4976       // One more try:  Various low-level checks bottom out in
4977       // uncommon traps.  If the debug-info of the trap omits
4978       // any reference to the allocation, as we've already
4979       // observed, then there can be no objection to the trap.
4980       bool found_trap = false;
4981       for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
4982         Node* obs = not_ctl->fast_out(j);
4983         if (obs->in(0) == not_ctl && obs->is_Call() &&
4984             (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
4985           found_trap = true; break;
4986         }
4987       }
4988       if (found_trap) {
4989         ctl = iff->in(0);       // This test feeds a harmless uncommon trap.
4990         continue;
4991       }
4992     }
4993     return NULL;
4994   }
4995 
4996   // If we get this far, we have an allocation which immediately
4997   // precedes the arraycopy, and we can take over zeroing the new object.
4998   // The arraycopy will finish the initialization, and provide
4999   // a new control state to which we will anchor the destination pointer.
5000 
5001   return alloc;
5002 }
5003 
5004 // Helper for initialization of arrays, creating a ClearArray.
5005 // It writes zero bits in [start..end), within the body of an array object.
5006 // The memory effects are all chained onto the 'adr_type' alias category.
5007 //
5008 // Since the object is otherwise uninitialized, we are free
5009 // to put a little "slop" around the edges of the cleared area,
5010 // as long as it does not go back into the array's header,
5011 // or beyond the array end within the heap.
5012 //
5013 // The lower edge can be rounded down to the nearest jint and the
5014 // upper edge can be rounded up to the nearest MinObjAlignmentInBytes.
5015 //
5016 // Arguments:
5017 //   adr_type           memory slice where writes are generated
5018 //   dest               oop of the destination array
5019 //   basic_elem_type    element type of the destination
5020 //   slice_idx          array index of first element to store
5021 //   slice_len          number of elements to store (or NULL)
5022 //   dest_size          total size in bytes of the array object
5023 //
5024 // Exactly one of slice_len or dest_size must be non-NULL.
5025 // If dest_size is non-NULL, zeroing extends to the end of the object.
5026 // If slice_len is non-NULL, the slice_idx value must be a constant.
5027 void
5028 LibraryCallKit::generate_clear_array(const TypePtr* adr_type,
5029                                      Node* dest,
5030                                      BasicType basic_elem_type,
5031                                      Node* slice_idx,
5032                                      Node* slice_len,
5033                                      Node* dest_size) {
5034   // one or the other but not both of slice_len and dest_size:
5035   assert((slice_len != NULL? 1: 0) + (dest_size != NULL? 1: 0) == 1, "");
5036   if (slice_len == NULL)  slice_len = top();
5037   if (dest_size == NULL)  dest_size = top();
5038 
5039   // operate on this memory slice:
5040   Node* mem = memory(adr_type); // memory slice to operate on
5041 
5042   // scaling and rounding of indexes:
5043   int scale = exact_log2(type2aelembytes(basic_elem_type));
5044   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
5045   int clear_low = (-1 << scale) & (BytesPerInt  - 1);
5046   int bump_bit  = (-1 << scale) & BytesPerInt;
5047 
5048   // determine constant starts and ends
5049   const intptr_t BIG_NEG = -128;
5050   assert(BIG_NEG + 2*abase < 0, "neg enough");
5051   intptr_t slice_idx_con = (intptr_t) find_int_con(slice_idx, BIG_NEG);
5052   intptr_t slice_len_con = (intptr_t) find_int_con(slice_len, BIG_NEG);
5053   if (slice_len_con == 0) {
5054     return;                     // nothing to do here
5055   }
5056   intptr_t start_con = (abase + (slice_idx_con << scale)) & ~clear_low;
5057   intptr_t end_con   = find_intptr_t_con(dest_size, -1);
5058   if (slice_idx_con >= 0 && slice_len_con >= 0) {
5059     assert(end_con < 0, "not two cons");
5060     end_con = round_to(abase + ((slice_idx_con + slice_len_con) << scale),
5061                        BytesPerLong);
5062   }
5063 
5064   if (start_con >= 0 && end_con >= 0) {
5065     // Constant start and end.  Simple.
5066     mem = ClearArrayNode::clear_memory(control(), mem, dest,
5067                                        start_con, end_con, &_gvn);
5068   } else if (start_con >= 0 && dest_size != top()) {
5069     // Constant start, pre-rounded end after the tail of the array.
5070     Node* end = dest_size;
5071     mem = ClearArrayNode::clear_memory(control(), mem, dest,
5072                                        start_con, end, &_gvn);
5073   } else if (start_con >= 0 && slice_len != top()) {
5074     // Constant start, non-constant end.  End needs rounding up.
5075     // End offset = round_up(abase + ((slice_idx_con + slice_len) << scale), 8)
5076     intptr_t end_base  = abase + (slice_idx_con << scale);
5077     int      end_round = (-1 << scale) & (BytesPerLong  - 1);
5078     Node*    end       = ConvI2X(slice_len);
5079     if (scale != 0)
5080       end = _gvn.transform( new(C,3) LShiftXNode(end, intcon(scale) ));
5081     end_base += end_round;
5082     end = _gvn.transform( new(C,3) AddXNode(end, MakeConX(end_base)) );
5083     end = _gvn.transform( new(C,3) AndXNode(end, MakeConX(~end_round)) );
5084     mem = ClearArrayNode::clear_memory(control(), mem, dest,
5085                                        start_con, end, &_gvn);
5086   } else if (start_con < 0 && dest_size != top()) {
5087     // Non-constant start, pre-rounded end after the tail of the array.
5088     // This is almost certainly a "round-to-end" operation.
5089     Node* start = slice_idx;
5090     start = ConvI2X(start);
5091     if (scale != 0)
5092       start = _gvn.transform( new(C,3) LShiftXNode( start, intcon(scale) ));
5093     start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(abase)) );
5094     if ((bump_bit | clear_low) != 0) {
5095       int to_clear = (bump_bit | clear_low);
5096       // Align up mod 8, then store a jint zero unconditionally
5097       // just before the mod-8 boundary.
5098       if (((abase + bump_bit) & ~to_clear) - bump_bit
5099           < arrayOopDesc::length_offset_in_bytes() + BytesPerInt) {
5100         bump_bit = 0;
5101         assert((abase & to_clear) == 0, "array base must be long-aligned");
5102       } else {
5103         // Bump 'start' up to (or past) the next jint boundary:
5104         start = _gvn.transform( new(C,3) AddXNode(start, MakeConX(bump_bit)) );
5105         assert((abase & clear_low) == 0, "array base must be int-aligned");
5106       }
5107       // Round bumped 'start' down to jlong boundary in body of array.
5108       start = _gvn.transform( new(C,3) AndXNode(start, MakeConX(~to_clear)) );
5109       if (bump_bit != 0) {
5110         // Store a zero to the immediately preceding jint:
5111         Node* x1 = _gvn.transform( new(C,3) AddXNode(start, MakeConX(-bump_bit)) );
5112         Node* p1 = basic_plus_adr(dest, x1);
5113         mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT);
5114         mem = _gvn.transform(mem);
5115       }
5116     }
5117     Node* end = dest_size; // pre-rounded
5118     mem = ClearArrayNode::clear_memory(control(), mem, dest,
5119                                        start, end, &_gvn);
5120   } else {
5121     // Non-constant start, unrounded non-constant end.
5122     // (Nobody zeroes a random midsection of an array using this routine.)
5123     ShouldNotReachHere();       // fix caller
5124   }
5125 
5126   // Done.
5127   set_memory(mem, adr_type);
5128 }
5129 
5130 
5131 bool
5132 LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type,
5133                                          BasicType basic_elem_type,
5134                                          AllocateNode* alloc,
5135                                          Node* src,  Node* src_offset,
5136                                          Node* dest, Node* dest_offset,
5137                                          Node* dest_size) {
5138   // See if there is an advantage from block transfer.
5139   int scale = exact_log2(type2aelembytes(basic_elem_type));
5140   if (scale >= LogBytesPerLong)
5141     return false;               // it is already a block transfer
5142 
5143   // Look at the alignment of the starting offsets.
5144   int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
5145   const intptr_t BIG_NEG = -128;
5146   assert(BIG_NEG + 2*abase < 0, "neg enough");
5147 
5148   intptr_t src_off  = abase + ((intptr_t) find_int_con(src_offset, -1)  << scale);
5149   intptr_t dest_off = abase + ((intptr_t) find_int_con(dest_offset, -1) << scale);
5150   if (src_off < 0 || dest_off < 0)
5151     // At present, we can only understand constants.
5152     return false;
5153 
5154   if (((src_off | dest_off) & (BytesPerLong-1)) != 0) {
5155     // Non-aligned; too bad.
5156     // One more chance:  Pick off an initial 32-bit word.
5157     // This is a common case, since abase can be odd mod 8.
5158     if (((src_off | dest_off) & (BytesPerLong-1)) == BytesPerInt &&
5159         ((src_off ^ dest_off) & (BytesPerLong-1)) == 0) {
5160       Node* sptr = basic_plus_adr(src,  src_off);
5161       Node* dptr = basic_plus_adr(dest, dest_off);
5162       Node* sval = make_load(control(), sptr, TypeInt::INT, T_INT, adr_type);
5163       store_to_memory(control(), dptr, sval, T_INT, adr_type);
5164       src_off += BytesPerInt;
5165       dest_off += BytesPerInt;
5166     } else {
5167       return false;
5168     }
5169   }
5170   assert(src_off % BytesPerLong == 0, "");
5171   assert(dest_off % BytesPerLong == 0, "");
5172 
5173   // Do this copy by giant steps.
5174   Node* sptr  = basic_plus_adr(src,  src_off);
5175   Node* dptr  = basic_plus_adr(dest, dest_off);
5176   Node* countx = dest_size;
5177   countx = _gvn.transform( new (C, 3) SubXNode(countx, MakeConX(dest_off)) );
5178   countx = _gvn.transform( new (C, 3) URShiftXNode(countx, intcon(LogBytesPerLong)) );
5179 
5180   bool disjoint_bases = true;   // since alloc != NULL
5181   generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases,
5182                                sptr, NULL, dptr, NULL, countx);
5183 
5184   return true;
5185 }
5186 
5187 
5188 // Helper function; generates code for the slow case.
5189 // We make a call to a runtime method which emulates the native method,
5190 // but without the native wrapper overhead.
5191 void
5192 LibraryCallKit::generate_slow_arraycopy(const TypePtr* adr_type,
5193                                         Node* src,  Node* src_offset,
5194                                         Node* dest, Node* dest_offset,
5195                                         Node* copy_length) {
5196   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON,
5197                                  OptoRuntime::slow_arraycopy_Type(),
5198                                  OptoRuntime::slow_arraycopy_Java(),
5199                                  "slow_arraycopy", adr_type,
5200                                  src, src_offset, dest, dest_offset,
5201                                  copy_length);
5202 
5203   // Handle exceptions thrown by this fellow:
5204   make_slow_call_ex(call, env()->Throwable_klass(), false);
5205 }
5206 
5207 // Helper function; generates code for cases requiring runtime checks.
5208 Node*
5209 LibraryCallKit::generate_checkcast_arraycopy(const TypePtr* adr_type,
5210                                              Node* dest_elem_klass,
5211                                              Node* src,  Node* src_offset,
5212                                              Node* dest, Node* dest_offset,
5213                                              Node* copy_length, bool need_pre_barrier) {
5214   if (stopped())  return NULL;
5215 
5216   address copyfunc_addr = StubRoutines::checkcast_arraycopy(need_pre_barrier);
5217   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
5218     return NULL;
5219   }
5220 
5221   // Pick out the parameters required to perform a store-check
5222   // for the target array.  This is an optimistic check.  It will
5223   // look in each non-null element's class, at the desired klass's
5224   // super_check_offset, for the desired klass.
5225   int sco_offset = Klass::super_check_offset_offset_in_bytes() + sizeof(oopDesc);
5226   Node* p3 = basic_plus_adr(dest_elem_klass, sco_offset);
5227   Node* n3 = new(C, 3) LoadINode(NULL, memory(p3), p3, _gvn.type(p3)->is_ptr());
5228   Node* check_offset = ConvI2X(_gvn.transform(n3));
5229   Node* check_value  = dest_elem_klass;
5230 
5231   Node* src_start  = array_element_address(src,  src_offset,  T_OBJECT);
5232   Node* dest_start = array_element_address(dest, dest_offset, T_OBJECT);
5233 
5234   // (We know the arrays are never conjoint, because their types differ.)
5235   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5236                                  OptoRuntime::checkcast_arraycopy_Type(),
5237                                  copyfunc_addr, "checkcast_arraycopy", adr_type,
5238                                  // five arguments, of which two are
5239                                  // intptr_t (jlong in LP64)
5240                                  src_start, dest_start,
5241                                  copy_length XTOP,
5242                                  check_offset XTOP,
5243                                  check_value);
5244 
5245   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
5246 }
5247 
5248 
5249 // Helper function; generates code for cases requiring runtime checks.
5250 Node*
5251 LibraryCallKit::generate_generic_arraycopy(const TypePtr* adr_type,
5252                                            Node* src,  Node* src_offset,
5253                                            Node* dest, Node* dest_offset,
5254                                            Node* copy_length) {
5255   if (stopped())  return NULL;
5256 
5257   address copyfunc_addr = StubRoutines::generic_arraycopy();
5258   if (copyfunc_addr == NULL) { // Stub was not generated, go slow path.
5259     return NULL;
5260   }
5261 
5262   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
5263                     OptoRuntime::generic_arraycopy_Type(),
5264                     copyfunc_addr, "generic_arraycopy", adr_type,
5265                     src, src_offset, dest, dest_offset, copy_length);
5266 
5267   return _gvn.transform(new (C, 1) ProjNode(call, TypeFunc::Parms));
5268 }
5269 
5270 // Helper function; generates the fast out-of-line call to an arraycopy stub.
5271 void
5272 LibraryCallKit::generate_unchecked_arraycopy(const TypePtr* adr_type,
5273                                              BasicType basic_elem_type,
5274                                              bool disjoint_bases,
5275                                              Node* src,  Node* src_offset,
5276                                              Node* dest, Node* dest_offset,
5277                                              Node* copy_length, bool need_pre_barrier) {
5278   if (stopped())  return;               // nothing to do
5279 
5280   Node* src_start  = src;
5281   Node* dest_start = dest;
5282   if (src_offset != NULL || dest_offset != NULL) {
5283     assert(src_offset != NULL && dest_offset != NULL, "");
5284     src_start  = array_element_address(src,  src_offset,  basic_elem_type);
5285     dest_start = array_element_address(dest, dest_offset, basic_elem_type);
5286   }
5287 
5288   // Figure out which arraycopy runtime method to call.
5289   const char* copyfunc_name = "arraycopy";
5290   address     copyfunc_addr =
5291       basictype2arraycopy(basic_elem_type, src_offset, dest_offset,
5292                           disjoint_bases, copyfunc_name, need_pre_barrier);
5293 
5294   // Call it.  Note that the count_ix value is not scaled to a byte-size.
5295   make_runtime_call(RC_LEAF|RC_NO_FP,
5296                     OptoRuntime::fast_arraycopy_Type(),
5297                     copyfunc_addr, copyfunc_name, adr_type,
5298                     src_start, dest_start, copy_length XTOP);
5299 }