< prev index next >

src/hotspot/share/opto/library_call.cpp

Print this page

   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 "asm/macroAssembler.hpp"



  26 #include "ci/ciSymbols.hpp"
  27 #include "ci/ciUtilities.inline.hpp"
  28 #include "classfile/vmIntrinsics.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "gc/shared/barrierSet.hpp"

  32 #include "jfr/support/jfrIntrinsics.hpp"
  33 #include "memory/resourceArea.hpp"

  34 #include "oops/klass.inline.hpp"

  35 #include "oops/objArrayKlass.hpp"
  36 #include "opto/addnode.hpp"
  37 #include "opto/arraycopynode.hpp"
  38 #include "opto/c2compiler.hpp"
  39 #include "opto/castnode.hpp"
  40 #include "opto/cfgnode.hpp"
  41 #include "opto/convertnode.hpp"
  42 #include "opto/countbitsnode.hpp"

  43 #include "opto/idealKit.hpp"

  44 #include "opto/library_call.hpp"
  45 #include "opto/mathexactnode.hpp"
  46 #include "opto/mulnode.hpp"
  47 #include "opto/narrowptrnode.hpp"
  48 #include "opto/opaquenode.hpp"

  49 #include "opto/parse.hpp"
  50 #include "opto/rootnode.hpp"
  51 #include "opto/runtime.hpp"
  52 #include "opto/subnode.hpp"

  53 #include "opto/vectornode.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "prims/jvmtiThreadState.hpp"
  56 #include "prims/unsafe.hpp"

  57 #include "runtime/jniHandles.inline.hpp"
  58 #include "runtime/mountUnmountDisabler.hpp"
  59 #include "runtime/objectMonitor.hpp"
  60 #include "runtime/sharedRuntime.hpp"
  61 #include "runtime/stubRoutines.hpp"

  62 #include "utilities/macros.hpp"
  63 #include "utilities/powerOfTwo.hpp"
  64 
  65 //---------------------------make_vm_intrinsic----------------------------
  66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  67   vmIntrinsicID id = m->intrinsic_id();
  68   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  69 
  70   if (!m->is_loaded()) {
  71     // Do not attempt to inline unloaded methods.
  72     return nullptr;
  73   }
  74 
  75   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  76   bool is_available = false;
  77 
  78   {
  79     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  80     // the compiler must transition to '_thread_in_vm' state because both
  81     // methods access VM-internal data.

 392   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 393   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 394   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 395   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 396   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 397   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 398   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 399   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 400   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 401 
 402   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 403   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 404   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 405   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 406   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 407   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 408   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 409   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 410   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 411 



 412   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 413   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 414   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 415   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 416   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 417 
 418   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 419   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 420   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 421   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 422   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 423   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 424   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 425   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 426   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 427   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 428   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 429   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 430   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 431   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);

 451   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 452   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 453   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 454 
 455   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 456   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 457   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 458   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 459 
 460   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 461   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 462   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 463   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 464   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 465 
 466   case vmIntrinsics::_loadFence:
 467   case vmIntrinsics::_storeFence:
 468   case vmIntrinsics::_storeStoreFence:
 469   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 470 





 471   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 472 
 473   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 474   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 475   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 476 
 477   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 478   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 479 
 480   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 481   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 482 
 483   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 484                                                                                                 "endFirstTransition", true);
 485   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 486                                                                                                   "startFinalTransition", true);
 487   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 488                                                                                                   "startTransition", false);
 489   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 490                                                                                                 "endTransition", false);

 499 #endif
 500   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 501   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 502   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 503   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 504   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 505   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 506   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 507   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 508   case vmIntrinsics::_getLength:                return inline_native_getLength();
 509   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 510   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 511   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 512   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 513   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 514   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 515   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 516 
 517   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 518   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);






 519 
 520   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 521 
 522   case vmIntrinsics::_isInstance:
 523   case vmIntrinsics::_isHidden:
 524   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 525 
 526   case vmIntrinsics::_floatToRawIntBits:
 527   case vmIntrinsics::_floatToIntBits:
 528   case vmIntrinsics::_intBitsToFloat:
 529   case vmIntrinsics::_doubleToRawLongBits:
 530   case vmIntrinsics::_doubleToLongBits:
 531   case vmIntrinsics::_longBitsToDouble:
 532   case vmIntrinsics::_floatToFloat16:
 533   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 534   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 535   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 536   case vmIntrinsics::_floatIsFinite:
 537   case vmIntrinsics::_floatIsInfinite:
 538   case vmIntrinsics::_doubleIsFinite:

2262     case vmIntrinsics::_remainderUnsigned_l: {
2263       zero_check_long(argument(2));
2264       // Compile-time detect of null-exception
2265       if (stopped()) {
2266         return true; // keep the graph constructed so far
2267       }
2268       n = new UModLNode(control(), argument(0), argument(2));
2269       break;
2270     }
2271     default:  fatal_unexpected_iid(id);  break;
2272   }
2273   set_result(_gvn.transform(n));
2274   return true;
2275 }
2276 
2277 //----------------------------inline_unsafe_access----------------------------
2278 
2279 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2280   // Attempt to infer a sharper value type from the offset and base type.
2281   ciKlass* sharpened_klass = nullptr;

2282 
2283   // See if it is an instance field, with an object type.
2284   if (alias_type->field() != nullptr) {
2285     if (alias_type->field()->type()->is_klass()) {
2286       sharpened_klass = alias_type->field()->type()->as_klass();

2287     }
2288   }
2289 
2290   const TypeOopPtr* result = nullptr;
2291   // See if it is a narrow oop array.
2292   if (adr_type->isa_aryptr()) {
2293     if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2294       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();

2295       if (elem_type != nullptr && elem_type->is_loaded()) {
2296         // Sharpen the value type.
2297         result = elem_type;
2298       }
2299     }
2300   }
2301 
2302   // The sharpened class might be unloaded if there is no class loader
2303   // contraint in place.
2304   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2305     // Sharpen the value type.
2306     result = TypeOopPtr::make_from_klass(sharpened_klass);



2307   }
2308   if (result != nullptr) {
2309 #ifndef PRODUCT
2310     if (C->print_intrinsics() || C->print_inlining()) {
2311       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2312       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2313     }
2314 #endif
2315   }
2316   return result;
2317 }
2318 
2319 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2320   switch (kind) {
2321       case Relaxed:
2322         return MO_UNORDERED;
2323       case Opaque:
2324         return MO_RELAXED;
2325       case Acquire:
2326         return MO_ACQUIRE;

2374 #endif // ASSERT
2375  }
2376 #endif //PRODUCT
2377 
2378   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2379 
2380   Node* receiver = argument(0);  // type: oop
2381 
2382   // Build address expression.
2383   Node* heap_base_oop = top();
2384 
2385   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2386   Node* base = argument(1);  // type: oop
2387   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2388   Node* offset = argument(2);  // type: long
2389   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2390   // to be plain byte offsets, which are also the same as those accepted
2391   // by oopDesc::field_addr.
2392   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2393          "fieldOffset must be byte-scaled");







































2394   // 32-bit machines ignore the high half!
2395   offset = ConvL2X(offset);
2396 
2397   // Save state and restore on bailout
2398   SavedState old_state(this);
2399 
2400   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2401   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2402 
2403   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2404     if (type != T_OBJECT) {
2405       decorators |= IN_NATIVE; // off-heap primitive access
2406     } else {
2407       return false; // off-heap oop accesses are not supported
2408     }
2409   } else {
2410     heap_base_oop = base; // on-heap or mixed access
2411   }
2412 
2413   // Can base be null? Otherwise, always on-heap access.

2417     decorators |= IN_HEAP;
2418   }
2419 
2420   Node* val = is_store ? argument(4) : nullptr;
2421 
2422   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2423   if (adr_type == TypePtr::NULL_PTR) {
2424     return false; // off-heap access with zero address
2425   }
2426 
2427   // Try to categorize the address.
2428   Compile::AliasType* alias_type = C->alias_type(adr_type);
2429   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2430 
2431   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2432       alias_type->adr_type() == TypeAryPtr::RANGE) {
2433     return false; // not supported
2434   }
2435 
2436   bool mismatched = false;
2437   BasicType bt = alias_type->basic_type();




























2438   if (bt != T_ILLEGAL) {
2439     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2440     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2441       // Alias type doesn't differentiate between byte[] and boolean[]).
2442       // Use address type to get the element type.
2443       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2444     }
2445     if (is_reference_type(bt, true)) {
2446       // accessing an array field with getReference is not a mismatch
2447       bt = T_OBJECT;
2448     }
2449     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2450       // Don't intrinsify mismatched object accesses
2451       return false;
2452     }
2453     mismatched = (bt != type);
2454   } else if (alias_type->adr_type()->isa_oopptr()) {
2455     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2456   }
2457 
2458   old_state.discard();
2459   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2460 
2461   if (mismatched) {
2462     decorators |= C2_MISMATCHED;
2463   }
2464 
2465   // First guess at the value type.
2466   const Type *value_type = Type::get_const_basic_type(type);
2467 
2468   // Figure out the memory ordering.
2469   decorators |= mo_decorator_for_access_kind(kind);
2470 
2471   if (!is_store && type == T_OBJECT) {
2472     const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2473     if (tjp != nullptr) {
2474       value_type = tjp;


2475     }
2476   }
2477 
2478   receiver = null_check(receiver);
2479   if (stopped()) {
2480     return true;
2481   }
2482   // Heap pointers get a null-check from the interpreter,
2483   // as a courtesy.  However, this is not guaranteed by Unsafe,
2484   // and it is not possible to fully distinguish unintended nulls
2485   // from intended ones in this API.
2486 
2487   if (!is_store) {
2488     Node* p = nullptr;
2489     // Try to constant fold a load from a constant field
2490     ciField* field = alias_type->field();
2491     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2492       // final or stable field
2493       p = make_constant_from_field(field, heap_base_oop);
2494     }
2495 
2496     if (p == nullptr) { // Could not constant fold the load
2497       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);





2498       // Normalize the value returned by getBoolean in the following cases
2499       if (type == T_BOOLEAN &&
2500           (mismatched ||
2501            heap_base_oop == top() ||                  // - heap_base_oop is null or
2502            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2503                                                       //   and the unsafe access is made to large offset
2504                                                       //   (i.e., larger than the maximum offset necessary for any
2505                                                       //   field access)
2506             ) {
2507           IdealKit ideal = IdealKit(this);
2508 #define __ ideal.
2509           IdealVariable normalized_result(ideal);
2510           __ declarations_done();
2511           __ set(normalized_result, p);
2512           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2513           __ set(normalized_result, ideal.ConI(1));
2514           ideal.end_if();
2515           final_sync(ideal);
2516           p = __ value(normalized_result);
2517 #undef __

2521       p = gvn().transform(new CastP2XNode(nullptr, p));
2522       p = ConvX2UL(p);
2523     }
2524     // The load node has the control of the preceding MemBarCPUOrder.  All
2525     // following nodes will have the control of the MemBarCPUOrder inserted at
2526     // the end of this method.  So, pushing the load onto the stack at a later
2527     // point is fine.
2528     set_result(p);
2529   } else {
2530     if (bt == T_ADDRESS) {
2531       // Repackage the long as a pointer.
2532       val = ConvL2X(val);
2533       val = gvn().transform(new CastX2PNode(val));
2534     }
2535     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2536   }
2537 
2538   return true;
2539 }
2540 









































































































































































2541 //----------------------------inline_unsafe_load_store----------------------------
2542 // This method serves a couple of different customers (depending on LoadStoreKind):
2543 //
2544 // LS_cmp_swap:
2545 //
2546 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2547 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2548 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2549 //
2550 // LS_cmp_swap_weak:
2551 //
2552 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2553 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2554 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2555 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2556 //
2557 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2558 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2559 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2560 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);

2723     }
2724     case LS_cmp_swap:
2725     case LS_cmp_swap_weak:
2726     case LS_get_add:
2727       break;
2728     default:
2729       ShouldNotReachHere();
2730   }
2731 
2732   // Null check receiver.
2733   receiver = null_check(receiver);
2734   if (stopped()) {
2735     return true;
2736   }
2737 
2738   int alias_idx = C->get_alias_index(adr_type);
2739 
2740   if (is_reference_type(type)) {
2741     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2742 













2743     // Transformation of a value which could be null pointer (CastPP #null)
2744     // could be delayed during Parse (for example, in adjust_map_after_if()).
2745     // Execute transformation here to avoid barrier generation in such case.
2746     if (_gvn.type(newval) == TypePtr::NULL_PTR)
2747       newval = _gvn.makecon(TypePtr::NULL_PTR);
2748 
2749     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2750       // Refine the value to a null constant, when it is known to be null
2751       oldval = _gvn.makecon(TypePtr::NULL_PTR);
2752     }
2753   }
2754 
2755   Node* result = nullptr;
2756   switch (kind) {
2757     case LS_cmp_exchange: {
2758       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2759                                             oldval, newval, value_type, type, decorators);
2760       break;
2761     }
2762     case LS_cmp_swap_weak:

2791   insert_mem_bar(Op_MemBarCPUOrder);
2792   switch(id) {
2793     case vmIntrinsics::_loadFence:
2794       insert_mem_bar(Op_LoadFence);
2795       return true;
2796     case vmIntrinsics::_storeFence:
2797       insert_mem_bar(Op_StoreFence);
2798       return true;
2799     case vmIntrinsics::_storeStoreFence:
2800       insert_mem_bar(Op_StoreStoreFence);
2801       return true;
2802     case vmIntrinsics::_fullFence:
2803       insert_mem_bar(Op_MemBarFull);
2804       return true;
2805     default:
2806       fatal_unexpected_iid(id);
2807       return false;
2808   }
2809 }
2810 






























































































2811 bool LibraryCallKit::inline_onspinwait() {
2812   insert_mem_bar(Op_OnSpinWait);
2813   return true;
2814 }
2815 
2816 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2817   if (!kls->is_Con()) {
2818     return true;
2819   }
2820   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2821   if (klsptr == nullptr) {
2822     return true;
2823   }
2824   ciInstanceKlass* ik = klsptr->instance_klass();
2825   // don't need a guard for a klass that is already initialized
2826   return !ik->is_initialized();
2827 }
2828 
2829 //----------------------------inline_unsafe_writeback0-------------------------
2830 // public native void Unsafe.writeback0(long address)

2909                     Deoptimization::Action_make_not_entrant);
2910     }
2911     if (stopped()) {
2912       return true;
2913     }
2914 #endif //INCLUDE_JVMTI
2915 
2916   Node* test = nullptr;
2917   if (LibraryCallKit::klass_needs_init_guard(kls)) {
2918     // Note:  The argument might still be an illegal value like
2919     // Serializable.class or Object[].class.   The runtime will handle it.
2920     // But we must make an explicit check for initialization.
2921     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
2922     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2923     // can generate code to load it as unsigned byte.
2924     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2925     Node* bits = intcon(InstanceKlass::fully_initialized);
2926     test = _gvn.transform(new SubINode(inst, bits));
2927     // The 'test' is non-zero if we need to take a slow path.
2928   }
2929 
2930   Node* obj = new_instance(kls, test);
2931   set_result(obj);
2932   return true;
2933 }
2934 
2935 //------------------------inline_native_time_funcs--------------
2936 // inline code for System.currentTimeMillis() and System.nanoTime()
2937 // these have the same type and signature
2938 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2939   const TypeFunc* tf = OptoRuntime::void_long_Type();
2940   const TypePtr* no_memory_effects = nullptr;
2941   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2942   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2943 #ifdef ASSERT
2944   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2945   assert(value_top == top(), "second value must be top");
2946 #endif
2947   set_result(value);
2948   return true;
2949 }

3725   Node* arr = argument(1);
3726   Node* thread = _gvn.transform(new ThreadLocalNode());
3727   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
3728   Node* thread_obj_handle
3729     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3730   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3731   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3732 
3733   // Change the _monitor_owner_id of the JavaThread
3734   Node* tid = load_field_from_object(arr, "tid", "J");
3735   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3736   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3737 
3738   JFR_ONLY(extend_setCurrentThread(thread, arr);)
3739   return true;
3740 }
3741 
3742 const Type* LibraryCallKit::scopedValueCache_type() {
3743   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3744   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3745   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3746 
3747   // Because we create the scopedValue cache lazily we have to make the
3748   // type of the result BotPTR.
3749   bool xk = etype->klass_is_exact();
3750   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3751   return objects_type;
3752 }
3753 
3754 Node* LibraryCallKit::scopedValueCache_helper() {
3755   Node* thread = _gvn.transform(new ThreadLocalNode());
3756   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
3757   // We cannot use immutable_memory() because we might flip onto a
3758   // different carrier thread, at which point we'll need to use that
3759   // carrier thread's cache.
3760   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3761   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3762   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3763 }
3764 
3765 //------------------------inline_native_scopedValueCache------------------
3766 bool LibraryCallKit::inline_native_scopedValueCache() {
3767   Node* cache_obj_handle = scopedValueCache_helper();
3768   const Type* objects_type = scopedValueCache_type();
3769   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3770 

3906   }
3907   return kls;
3908 }
3909 
3910 //--------------------(inline_native_Class_query helpers)---------------------
3911 // Use this for JVM_ACC_INTERFACE.
3912 // Fall through if (mods & mask) == bits, take the guard otherwise.
3913 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
3914                                                  ByteSize offset, const Type* type, BasicType bt) {
3915   // Branch around if the given klass has the given modifier bit set.
3916   // Like generate_guard, adds a new path onto the region.
3917   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
3918   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
3919   Node* mask = intcon(modifier_mask);
3920   Node* bits = intcon(modifier_bits);
3921   Node* mbit = _gvn.transform(new AndINode(mods, mask));
3922   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
3923   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3924   return generate_fair_guard(bol, region);
3925 }

3926 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
3927   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
3928                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
3929 }
3930 
3931 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
3932 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
3933   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
3934                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
3935 }
3936 
3937 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
3938   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
3939 }
3940 
3941 //-------------------------inline_native_Class_query-------------------
3942 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
3943   const Type* return_type = TypeInt::BOOL;
3944   Node* prim_return_value = top();  // what happens if it's a primitive class?
3945   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);

4031 
4032 
4033   case vmIntrinsics::_getSuperclass:
4034     // The rules here are somewhat unfortunate, but we can still do better
4035     // with random logic than with a JNI call.
4036     // Interfaces store null or Object as _super, but must report null.
4037     // Arrays store an intermediate super as _super, but must report Object.
4038     // Other types can report the actual _super.
4039     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4040     if (generate_array_guard(kls, region) != nullptr) {
4041       // A guard was added.  If the guard is taken, it was an array.
4042       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4043     }
4044     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4045     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4046     if (generate_interface_guard(kls, region) != nullptr) {
4047       // A guard was added.  If the guard is taken, it was an interface.
4048       phi->add_req(null());
4049     }
4050     // If we fall through, it's a plain class.  Get its _super.
4051     p = off_heap_plus_addr(kls, in_bytes(Klass::super_offset()));
4052     kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4053     null_ctl = top();
4054     kls = null_check_oop(kls, &null_ctl);
4055     if (null_ctl != top()) {
4056       // If the guard is taken, Object.superClass is null (both klass and mirror).
4057       region->add_req(null_ctl);
4058       phi   ->add_req(null());
4059     }
4060     if (!stopped()) {
4061       query_value = load_mirror_from_klass(kls);











4062     }
4063     break;
4064 
4065   default:
4066     fatal_unexpected_iid(id);
4067     break;
4068   }
4069 
4070   // Fall-through is the normal case of a query to a real class.
4071   phi->init_req(1, query_value);
4072   region->init_req(1, control());
4073 
4074   C->set_has_split_ifs(true); // Has chance for split-if optimization
4075   set_result(region, phi);
4076   return true;
4077 }
4078 

4079 //-------------------------inline_Class_cast-------------------
4080 bool LibraryCallKit::inline_Class_cast() {
4081   Node* mirror = argument(0); // Class
4082   Node* obj    = argument(1);
4083   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4084   if (mirror_con == nullptr) {
4085     return false;  // dead path (mirror->is_top()).
4086   }
4087   if (obj == nullptr || obj->is_top()) {
4088     return false;  // dead path
4089   }
4090   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4091 
4092   // First, see if Class.cast() can be folded statically.
4093   // java_mirror_type() returns non-null for compile-time Class constants.
4094   ciType* tm = mirror_con->java_mirror_type();
4095   if (tm != nullptr && tm->is_klass() &&
4096       tp != nullptr) {
4097     if (!tp->is_loaded()) {
4098       // Don't use intrinsic when class is not loaded.
4099       return false;
4100     } else {
4101       int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());

4102       if (static_res == Compile::SSC_always_true) {
4103         // isInstance() is true - fold the code.
4104         set_result(obj);
4105         return true;
4106       } else if (static_res == Compile::SSC_always_false) {
4107         // Don't use intrinsic, have to throw ClassCastException.
4108         // If the reference is null, the non-intrinsic bytecode will
4109         // be optimized appropriately.
4110         return false;
4111       }
4112     }
4113   }
4114 
4115   // Bailout intrinsic and do normal inlining if exception path is frequent.
4116   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4117     return false;
4118   }
4119 
4120   // Generate dynamic checks.
4121   // Class.cast() is java implementation of _checkcast bytecode.
4122   // Do checkcast (Parse::do_checkcast()) optimizations here.
4123 
4124   mirror = null_check(mirror);
4125   // If mirror is dead, only null-path is taken.
4126   if (stopped()) {
4127     return true;
4128   }
4129 
4130   // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4131   enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4132   RegionNode* region = new RegionNode(PATH_LIMIT);
4133   record_for_igvn(region);
4134 
4135   // Now load the mirror's klass metaobject, and null-check it.
4136   // If kls is null, we have a primitive mirror and
4137   // nothing is an instance of a primitive type.
4138   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4139 
4140   Node* res = top();




4141   if (!stopped()) {

4142     Node* bad_type_ctrl = top();
4143     // Do checkcast optimizations.
4144     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4145     region->init_req(_bad_type_path, bad_type_ctrl);
4146   }
4147   if (region->in(_prim_path) != top() ||
4148       region->in(_bad_type_path) != top()) {

4149     // Let Interpreter throw ClassCastException.
4150     PreserveJVMState pjvms(this);




4151     set_control(_gvn.transform(region));



4152     uncommon_trap(Deoptimization::Reason_intrinsic,
4153                   Deoptimization::Action_maybe_recompile);
4154   }
4155   if (!stopped()) {
4156     set_result(res);
4157   }
4158   return true;
4159 }
4160 
4161 
4162 //--------------------------inline_native_subtype_check------------------------
4163 // This intrinsic takes the JNI calls out of the heart of
4164 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4165 bool LibraryCallKit::inline_native_subtype_check() {
4166   // Pull both arguments off the stack.
4167   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4168   args[0] = argument(0);
4169   args[1] = argument(1);
4170   Node* klasses[2];             // corresponding Klasses: superk, subk
4171   klasses[0] = klasses[1] = top();
4172 
4173   enum {
4174     // A full decision tree on {superc is prim, subc is prim}:
4175     _prim_0_path = 1,           // {P,N} => false
4176                                 // {P,P} & superc!=subc => false
4177     _prim_same_path,            // {P,P} & superc==subc => true
4178     _prim_1_path,               // {N,P} => false
4179     _ref_subtype_path,          // {N,N} & subtype check wins => true
4180     _both_ref_path,             // {N,N} & subtype check loses => false
4181     PATH_LIMIT
4182   };
4183 
4184   RegionNode* region = new RegionNode(PATH_LIMIT);

4185   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4186   record_for_igvn(region);

4187 
4188   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4189   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4190   int class_klass_offset = java_lang_Class::klass_offset();
4191 
4192   // First null-check both mirrors and load each mirror's klass metaobject.
4193   int which_arg;
4194   for (which_arg = 0; which_arg <= 1; which_arg++) {
4195     Node* arg = args[which_arg];
4196     arg = null_check(arg);
4197     if (stopped())  break;
4198     args[which_arg] = arg;
4199 
4200     Node* p = basic_plus_adr(arg, class_klass_offset);
4201     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4202     klasses[which_arg] = _gvn.transform(kls);
4203   }
4204 
4205   // Having loaded both klasses, test each for null.
4206   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4207   for (which_arg = 0; which_arg <= 1; which_arg++) {
4208     Node* kls = klasses[which_arg];
4209     Node* null_ctl = top();
4210     kls = null_check_oop(kls, &null_ctl, never_see_null);
4211     int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4212     region->init_req(prim_path, null_ctl);



4213     if (stopped())  break;
4214     klasses[which_arg] = kls;
4215   }
4216 
4217   if (!stopped()) {
4218     // now we have two reference types, in klasses[0..1]
4219     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4220     Node* superk = klasses[0];  // the receiver
4221     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4222     // now we have a successful reference subtype check
4223     region->set_req(_ref_subtype_path, control());
4224   }
4225 
4226   // If both operands are primitive (both klasses null), then
4227   // we must return true when they are identical primitives.
4228   // It is convenient to test this after the first null klass check.
4229   set_control(region->in(_prim_0_path)); // go back to first null check

4230   if (!stopped()) {
4231     // Since superc is primitive, make a guard for the superc==subc case.
4232     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4233     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4234     generate_guard(bol_eq, region, PROB_FAIR);
4235     if (region->req() == PATH_LIMIT+1) {
4236       // A guard was added.  If the added guard is taken, superc==subc.
4237       region->swap_edges(PATH_LIMIT, _prim_same_path);
4238       region->del_req(PATH_LIMIT);
4239     }
4240     region->set_req(_prim_0_path, control()); // Not equal after all.
4241   }
4242 
4243   // these are the only paths that produce 'true':
4244   phi->set_req(_prim_same_path,   intcon(1));
4245   phi->set_req(_ref_subtype_path, intcon(1));
4246 
4247   // pull together the cases:
4248   assert(region->req() == PATH_LIMIT, "sane region");
4249   for (uint i = 1; i < region->req(); i++) {
4250     Node* ctl = region->in(i);
4251     if (ctl == nullptr || ctl == top()) {
4252       region->set_req(i, top());
4253       phi   ->set_req(i, top());
4254     } else if (phi->in(i) == nullptr) {
4255       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4256     }
4257   }
4258 
4259   set_control(_gvn.transform(region));
4260   set_result(_gvn.transform(phi));
4261   return true;
4262 }
4263 
4264 //---------------------generate_array_guard_common------------------------
4265 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4266                                                   bool obj_array, bool not_array, Node** obj) {
4267 
4268   if (stopped()) {
4269     return nullptr;
4270   }
4271 
4272   // If obj_array/non_array==false/false:
4273   // Branch around if the given klass is in fact an array (either obj or prim).
4274   // If obj_array/non_array==false/true:
4275   // Branch around if the given klass is not an array klass of any kind.
4276   // If obj_array/non_array==true/true:
4277   // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4278   // If obj_array/non_array==true/false:
4279   // Branch around if the kls is an oop array (Object[] or subtype)
4280   //
4281   // Like generate_guard, adds a new path onto the region.
4282   jint  layout_con = 0;
4283   Node* layout_val = get_layout_helper(kls, layout_con);
4284   if (layout_val == nullptr) {
4285     bool query = (obj_array
4286                   ? Klass::layout_helper_is_objArray(layout_con)
4287                   : Klass::layout_helper_is_array(layout_con));
4288     if (query == not_array) {







4289       return nullptr;                       // never a branch
4290     } else {                             // always a branch
4291       Node* always_branch = control();
4292       if (region != nullptr)
4293         region->add_req(always_branch);
4294       set_control(top());
4295       return always_branch;
4296     }
4297   }





















4298   // Now test the correct condition.
4299   jint  nval = (obj_array
4300                 ? (jint)(Klass::_lh_array_tag_type_value
4301                    <<    Klass::_lh_array_tag_shift)
4302                 : Klass::_lh_neutral_value);
4303   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4304   BoolTest::mask btest = BoolTest::lt;  // correct for testing is_[obj]array
4305   // invert the test if we are looking for a non-array
4306   if (not_array)  btest = BoolTest(btest).negate();
4307   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4308   Node* ctrl = generate_fair_guard(bol, region);
4309   Node* is_array_ctrl = not_array ? control() : ctrl;
4310   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4311     // Keep track of the fact that 'obj' is an array to prevent
4312     // array specific accesses from floating above the guard.
4313     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4314   }
4315   return ctrl;
4316 }
4317 




































































































































4318 
4319 //-----------------------inline_native_newArray--------------------------
4320 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4321 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4322 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4323   Node* mirror;
4324   Node* count_val;
4325   if (uninitialized) {
4326     null_check_receiver();
4327     mirror    = argument(1);
4328     count_val = argument(2);
4329   } else {
4330     mirror    = argument(0);
4331     count_val = argument(1);
4332   }
4333 
4334   mirror = null_check(mirror);
4335   // If mirror or obj is dead, only null-path is taken.
4336   if (stopped())  return true;
4337 
4338   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4339   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4340   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);

4358     CallJavaNode* slow_call = nullptr;
4359     if (uninitialized) {
4360       // Generate optimized virtual call (holder class 'Unsafe' is final)
4361       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4362     } else {
4363       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4364     }
4365     Node* slow_result = set_results_for_java_call(slow_call);
4366     // this->control() comes from set_results_for_java_call
4367     result_reg->set_req(_slow_path, control());
4368     result_val->set_req(_slow_path, slow_result);
4369     result_io ->set_req(_slow_path, i_o());
4370     result_mem->set_req(_slow_path, reset_memory());
4371   }
4372 
4373   set_control(normal_ctl);
4374   if (!stopped()) {
4375     // Normal case:  The array type has been cached in the java.lang.Class.
4376     // The following call works fine even if the array type is polymorphic.
4377     // It could be a dynamic mix of int[], boolean[], Object[], etc.



4378     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4379     result_reg->init_req(_normal_path, control());
4380     result_val->init_req(_normal_path, obj);
4381     result_io ->init_req(_normal_path, i_o());
4382     result_mem->init_req(_normal_path, reset_memory());
4383 
4384     if (uninitialized) {
4385       // Mark the allocation so that zeroing is skipped
4386       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4387       alloc->maybe_set_complete(&_gvn);
4388     }
4389   }
4390 
4391   // Return the combined state.
4392   set_i_o(        _gvn.transform(result_io)  );
4393   set_all_memory( _gvn.transform(result_mem));
4394 
4395   C->set_has_split_ifs(true); // Has chance for split-if optimization
4396   set_result(result_reg, result_val);
4397   return true;

4446   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4447   { PreserveReexecuteState preexecs(this);
4448     jvms()->set_should_reexecute(true);
4449 
4450     array_type_mirror = null_check(array_type_mirror);
4451     original          = null_check(original);
4452 
4453     // Check if a null path was taken unconditionally.
4454     if (stopped())  return true;
4455 
4456     Node* orig_length = load_array_length(original);
4457 
4458     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4459     klass_node = null_check(klass_node);
4460 
4461     RegionNode* bailout = new RegionNode(1);
4462     record_for_igvn(bailout);
4463 
4464     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4465     // Bail out if that is so.
4466     Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);















4467     if (not_objArray != nullptr) {
4468       // Improve the klass node's type from the new optimistic assumption:
4469       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4470       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4471       Node* cast = new CastPPNode(control(), klass_node, akls);
4472       klass_node = _gvn.transform(cast);


4473     }
4474 
4475     // Bail out if either start or end is negative.
4476     generate_negative_guard(start, bailout, &start);
4477     generate_negative_guard(end,   bailout, &end);
4478 
4479     Node* length = end;
4480     if (_gvn.type(start) != TypeInt::ZERO) {
4481       length = _gvn.transform(new SubINode(end, start));
4482     }
4483 
4484     // Bail out if length is negative (i.e., if start > end).
4485     // Without this the new_array would throw
4486     // NegativeArraySizeException but IllegalArgumentException is what
4487     // should be thrown
4488     generate_negative_guard(length, bailout, &length);
4489 







































4490     // Bail out if start is larger than the original length
4491     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4492     generate_negative_guard(orig_tail, bailout, &orig_tail);
4493 
4494     if (bailout->req() > 1) {
4495       PreserveJVMState pjvms(this);
4496       set_control(_gvn.transform(bailout));
4497       uncommon_trap(Deoptimization::Reason_intrinsic,
4498                     Deoptimization::Action_maybe_recompile);
4499     }
4500 
4501     if (!stopped()) {
4502       // How many elements will we copy from the original?
4503       // The answer is MinI(orig_tail, length).
4504       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4505 
4506       // Generate a direct call to the right arraycopy function(s).
4507       // We know the copy is disjoint but we might not know if the
4508       // oop stores need checking.
4509       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).

4515       // to the copyOf to be validated, including that the copy to the
4516       // new array won't trigger an ArrayStoreException. That subtype
4517       // check can be optimized if we know something on the type of
4518       // the input array from type speculation.
4519       if (_gvn.type(klass_node)->singleton()) {
4520         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4521         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4522 
4523         int test = C->static_subtype_check(superk, subk);
4524         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4525           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4526           if (t_original->speculative_type() != nullptr) {
4527             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4528           }
4529         }
4530       }
4531 
4532       bool validated = false;
4533       // Reason_class_check rather than Reason_intrinsic because we
4534       // want to intrinsify even if this traps.
4535       if (!too_many_traps(Deoptimization::Reason_class_check)) {
4536         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4537 
4538         if (not_subtype_ctrl != top()) {
4539           PreserveJVMState pjvms(this);
4540           set_control(not_subtype_ctrl);
4541           uncommon_trap(Deoptimization::Reason_class_check,
4542                         Deoptimization::Action_make_not_entrant);
4543           assert(stopped(), "Should be stopped");
4544         }
4545         validated = true;
4546       }
4547 
4548       if (!stopped()) {
4549         newcopy = new_array(klass_node, length, 0);  // no arguments to push
4550 
4551         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4552                                                 load_object_klass(original), klass_node);
4553         if (!is_copyOfRange) {
4554           ac->set_copyof(validated);
4555         } else {
4556           ac->set_copyofrange(validated);
4557         }
4558         Node* n = _gvn.transform(ac);
4559         if (n == ac) {
4560           ac->connect_outputs(this);
4561         } else {
4562           assert(validated, "shouldn't transform if all arguments not validated");
4563           set_all_memory(n);
4564         }
4565       }
4566     }
4567   } // original reexecute is set back here
4568 
4569   C->set_has_split_ifs(true); // Has chance for split-if optimization

4601 
4602 //-----------------------generate_method_call----------------------------
4603 // Use generate_method_call to make a slow-call to the real
4604 // method if the fast path fails.  An alternative would be to
4605 // use a stub like OptoRuntime::slow_arraycopy_Java.
4606 // This only works for expanding the current library call,
4607 // not another intrinsic.  (E.g., don't use this for making an
4608 // arraycopy call inside of the copyOf intrinsic.)
4609 CallJavaNode*
4610 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4611   // When compiling the intrinsic method itself, do not use this technique.
4612   guarantee(callee() != C->method(), "cannot make slow-call to self");
4613 
4614   ciMethod* method = callee();
4615   // ensure the JVMS we have will be correct for this call
4616   guarantee(method_id == method->intrinsic_id(), "must match");
4617 
4618   const TypeFunc* tf = TypeFunc::make(method);
4619   if (res_not_null) {
4620     assert(tf->return_type() == T_OBJECT, "");
4621     const TypeTuple* range = tf->range();
4622     const Type** fields = TypeTuple::fields(range->cnt());
4623     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4624     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4625     tf = TypeFunc::make(tf->domain(), new_range);
4626   }
4627   CallJavaNode* slow_call;
4628   if (is_static) {
4629     assert(!is_virtual, "");
4630     slow_call = new CallStaticJavaNode(C, tf,
4631                            SharedRuntime::get_resolve_static_call_stub(), method);
4632   } else if (is_virtual) {
4633     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4634     int vtable_index = Method::invalid_vtable_index;
4635     if (UseInlineCaches) {
4636       // Suppress the vtable call
4637     } else {
4638       // hashCode and clone are not a miranda methods,
4639       // so the vtable index is fixed.
4640       // No need to use the linkResolver to get it.
4641        vtable_index = method->vtable_index();
4642        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4643               "bad index %d", vtable_index);
4644     }
4645     slow_call = new CallDynamicJavaNode(tf,

4662   set_edges_for_java_call(slow_call);
4663   return slow_call;
4664 }
4665 
4666 
4667 /**
4668  * Build special case code for calls to hashCode on an object. This call may
4669  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4670  * slightly different code.
4671  */
4672 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4673   assert(is_static == callee()->is_static(), "correct intrinsic selection");
4674   assert(!(is_virtual && is_static), "either virtual, special, or static");
4675 
4676   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4677 
4678   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4679   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
4680   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4681   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4682   Node* obj = nullptr;







4683   if (!is_static) {
4684     // Check for hashing null object
4685     obj = null_check_receiver();
4686     if (stopped())  return true;        // unconditionally null
4687     result_reg->init_req(_null_path, top());
4688     result_val->init_req(_null_path, top());
4689   } else {
4690     // Do a null check, and return zero if null.
4691     // System.identityHashCode(null) == 0
4692     obj = argument(0);
4693     Node* null_ctl = top();
4694     obj = null_check_oop(obj, &null_ctl);
4695     result_reg->init_req(_null_path, null_ctl);
4696     result_val->init_req(_null_path, _gvn.intcon(0));
4697   }
4698 
4699   // Unconditionally null?  Then return right away.
4700   if (stopped()) {
4701     set_control( result_reg->in(_null_path));
4702     if (!stopped())
4703       set_result(result_val->in(_null_path));
4704     return true;
4705   }
4706 
4707   // We only go to the fast case code if we pass a number of guards.  The
4708   // paths which do not pass are accumulated in the slow_region.
4709   RegionNode* slow_region = new RegionNode(1);
4710   record_for_igvn(slow_region);
4711 
4712   // If this is a virtual call, we generate a funny guard.  We pull out
4713   // the vtable entry corresponding to hashCode() from the target object.
4714   // If the target method which we are calling happens to be the native
4715   // Object hashCode() method, we pass the guard.  We do not need this
4716   // guard for non-virtual calls -- the caller is known to be the native
4717   // Object hashCode().
4718   if (is_virtual) {
4719     // After null check, get the object's klass.
4720     Node* obj_klass = load_object_klass(obj);
4721     generate_virtual_guard(obj_klass, slow_region);
4722   }
4723 
4724   // Get the header out of the object, use LoadMarkNode when available
4725   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4726   // The control of the load must be null. Otherwise, the load can move before
4727   // the null check after castPP removal.
4728   Node* no_ctrl = nullptr;
4729   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4730 
4731   if (!UseObjectMonitorTable) {
4732     // Test the header to see if it is safe to read w.r.t. locking.


4733     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
4734     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4735     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
4736     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4737     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4738 
4739     generate_slow_guard(test_monitor, slow_region);
4740   }
4741 
4742   // Get the hash value and check to see that it has been properly assigned.
4743   // We depend on hash_mask being at most 32 bits and avoid the use of
4744   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4745   // vm: see markWord.hpp.
4746   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
4747   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
4748   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4749   // This hack lets the hash bits live anywhere in the mark object now, as long
4750   // as the shift drops the relevant bits into the low 32 bits.  Note that
4751   // Java spec says that HashCode is an int so there's no point in capturing
4752   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).

4780     // this->control() comes from set_results_for_java_call
4781     result_reg->init_req(_slow_path, control());
4782     result_val->init_req(_slow_path, slow_result);
4783     result_io  ->set_req(_slow_path, i_o());
4784     result_mem ->set_req(_slow_path, reset_memory());
4785   }
4786 
4787   // Return the combined state.
4788   set_i_o(        _gvn.transform(result_io)  );
4789   set_all_memory( _gvn.transform(result_mem));
4790 
4791   set_result(result_reg, result_val);
4792   return true;
4793 }
4794 
4795 //---------------------------inline_native_getClass----------------------------
4796 // public final native Class<?> java.lang.Object.getClass();
4797 //
4798 // Build special case code for calls to getClass on an object.
4799 bool LibraryCallKit::inline_native_getClass() {
4800   Node* obj = null_check_receiver();









4801   if (stopped())  return true;
4802   set_result(load_mirror_from_klass(load_object_klass(obj)));
4803   return true;
4804 }
4805 
4806 //-----------------inline_native_Reflection_getCallerClass---------------------
4807 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4808 //
4809 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4810 //
4811 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4812 // in that it must skip particular security frames and checks for
4813 // caller sensitive methods.
4814 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4815 #ifndef PRODUCT
4816   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4817     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4818   }
4819 #endif
4820 

5202 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5203 //
5204 // The general case has two steps, allocation and copying.
5205 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5206 //
5207 // Copying also has two cases, oop arrays and everything else.
5208 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5209 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5210 //
5211 // These steps fold up nicely if and when the cloned object's klass
5212 // can be sharply typed as an object array, a type array, or an instance.
5213 //
5214 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5215   PhiNode* result_val;
5216 
5217   // Set the reexecute bit for the interpreter to reexecute
5218   // the bytecode that invokes Object.clone if deoptimization happens.
5219   { PreserveReexecuteState preexecs(this);
5220     jvms()->set_should_reexecute(true);
5221 
5222     Node* obj = null_check_receiver();

5223     if (stopped())  return true;
5224 
5225     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();






5226 
5227     // If we are going to clone an instance, we need its exact type to
5228     // know the number and types of fields to convert the clone to
5229     // loads/stores. Maybe a speculative type can help us.
5230     if (!obj_type->klass_is_exact() &&
5231         obj_type->speculative_type() != nullptr &&
5232         obj_type->speculative_type()->is_instance_klass()) {

5233       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5234       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5235           !spec_ik->has_injected_fields()) {
5236         if (!obj_type->isa_instptr() ||
5237             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5238           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5239         }
5240       }
5241     }
5242 
5243     // Conservatively insert a memory barrier on all memory slices.
5244     // Do not let writes into the original float below the clone.
5245     insert_mem_bar(Op_MemBarCPUOrder);
5246 
5247     // paths into result_reg:
5248     enum {
5249       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5250       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5251       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5252       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5253       PATH_LIMIT
5254     };
5255     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5256     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5257     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5258     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5259     record_for_igvn(result_reg);
5260 
5261     Node* obj_klass = load_object_klass(obj);





5262     Node* array_obj = obj;
5263     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5264     if (array_ctl != nullptr) {
5265       // It's an array.
5266       PreserveJVMState pjvms(this);
5267       set_control(array_ctl);
5268       Node* obj_length = load_array_length(array_obj);
5269       Node* array_size = nullptr; // Size of the array without object alignment padding.
5270       Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5271 
5272       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5273       if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5274         // If it is an oop array, it requires very special treatment,
5275         // because gc barriers are required when accessing the array.
5276         Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5277         if (is_obja != nullptr) {
5278           PreserveJVMState pjvms2(this);
5279           set_control(is_obja);
5280           // Generate a direct call to the right arraycopy function(s).
5281           // Clones are always tightly coupled.
5282           ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5283           ac->set_clone_oop_array();
5284           Node* n = _gvn.transform(ac);
5285           assert(n == ac, "cannot disappear");
5286           ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5287 
5288           result_reg->init_req(_objArray_path, control());
5289           result_val->init_req(_objArray_path, alloc_obj);
5290           result_i_o ->set_req(_objArray_path, i_o());
5291           result_mem ->set_req(_objArray_path, reset_memory());
5292         }
5293       }
5294       // Otherwise, there are no barriers to worry about.
5295       // (We can dispense with card marks if we know the allocation
5296       //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5297       //  causes the non-eden paths to take compensating steps to
5298       //  simulate a fresh allocation, so that no further
5299       //  card marks are required in compiled code to initialize
5300       //  the object.)
5301 
5302       if (!stopped()) {
5303         copy_to_clone(array_obj, alloc_obj, array_size, true);
5304 
5305         // Present the results of the copy.
5306         result_reg->init_req(_array_path, control());
5307         result_val->init_req(_array_path, alloc_obj);
5308         result_i_o ->set_req(_array_path, i_o());
5309         result_mem ->set_req(_array_path, reset_memory());




































5310       }
5311     }
5312 
5313     // We only go to the instance fast case code if we pass a number of guards.
5314     // The paths which do not pass are accumulated in the slow_region.
5315     RegionNode* slow_region = new RegionNode(1);
5316     record_for_igvn(slow_region);
5317     if (!stopped()) {
5318       // It's an instance (we did array above).  Make the slow-path tests.
5319       // If this is a virtual call, we generate a funny guard.  We grab
5320       // the vtable entry corresponding to clone() from the target object.
5321       // If the target method which we are calling happens to be the
5322       // Object clone() method, we pass the guard.  We do not need this
5323       // guard for non-virtual calls; the caller is known to be the native
5324       // Object clone().
5325       if (is_virtual) {
5326         generate_virtual_guard(obj_klass, slow_region);
5327       }
5328 
5329       // The object must be easily cloneable and must not have a finalizer.
5330       // Both of these conditions may be checked in a single test.
5331       // We could optimize the test further, but we don't care.
5332       generate_misc_flags_guard(obj_klass,
5333                                 // Test both conditions:
5334                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5335                                 // Must be cloneable but not finalizer:
5336                                 KlassFlags::_misc_is_cloneable_fast,

5428         set_jvms(sfpt->jvms());
5429         _reexecute_sp = jvms()->sp();
5430 
5431         return saved_jvms;
5432       }
5433     }
5434   }
5435   return nullptr;
5436 }
5437 
5438 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5439 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5440 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5441   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5442   uint size = alloc->req();
5443   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5444   old_jvms->set_map(sfpt);
5445   for (uint i = 0; i < size; i++) {
5446     sfpt->init_req(i, alloc->in(i));
5447   }












5448   // re-push array length for deoptimization
5449   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5450   old_jvms->set_sp(old_jvms->sp()+1);
5451   old_jvms->set_monoff(old_jvms->monoff()+1);
5452   old_jvms->set_scloff(old_jvms->scloff()+1);
5453   old_jvms->set_endoff(old_jvms->endoff()+1);











5454   old_jvms->set_should_reexecute(true);
5455 
5456   sfpt->set_i_o(map()->i_o());
5457   sfpt->set_memory(map()->memory());
5458   sfpt->set_control(map()->control());
5459   return sfpt;
5460 }
5461 
5462 // In case of a deoptimization, we restart execution at the
5463 // allocation, allocating a new array. We would leave an uninitialized
5464 // array in the heap that GCs wouldn't expect. Move the allocation
5465 // after the traps so we don't allocate the array if we
5466 // deoptimize. This is possible because tightly_coupled_allocation()
5467 // guarantees there's no observer of the allocated array at this point
5468 // and the control flow is simple enough.
5469 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5470                                                     int saved_reexecute_sp, uint new_idx) {
5471   if (saved_jvms_before_guards != nullptr && !stopped()) {
5472     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5473 
5474     assert(alloc != nullptr, "only with a tightly coupled allocation");
5475     // restore JVM state to the state at the arraycopy
5476     saved_jvms_before_guards->map()->set_control(map()->control());
5477     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5478     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5479     // If we've improved the types of some nodes (null check) while
5480     // emitting the guards, propagate them to the current state
5481     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5482     set_jvms(saved_jvms_before_guards);
5483     _reexecute_sp = saved_reexecute_sp;
5484 
5485     // Remove the allocation from above the guards
5486     CallProjections callprojs;
5487     alloc->extract_projections(&callprojs, true);
5488     InitializeNode* init = alloc->initialization();
5489     Node* alloc_mem = alloc->in(TypeFunc::Memory);
5490     C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5491     init->replace_mem_projs_by(alloc_mem, C);
5492 
5493     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5494     // the allocation (i.e. is only valid if the allocation succeeds):
5495     // 1) replace CastIINode with AllocateArrayNode's length here
5496     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5497     //
5498     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5499     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5500     Node* init_control = init->proj_out(TypeFunc::Control);
5501     Node* alloc_length = alloc->Ideal_length();
5502 #ifdef ASSERT
5503     Node* prev_cast = nullptr;
5504 #endif
5505     for (uint i = 0; i < init_control->outcnt(); i++) {
5506       Node* init_out = init_control->raw_out(i);
5507       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5508 #ifdef ASSERT
5509         if (prev_cast == nullptr) {
5510           prev_cast = init_out;

5512           if (prev_cast->cmp(*init_out) == false) {
5513             prev_cast->dump();
5514             init_out->dump();
5515             assert(false, "not equal CastIINode");
5516           }
5517         }
5518 #endif
5519         C->gvn_replace_by(init_out, alloc_length);
5520       }
5521     }
5522     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5523 
5524     // move the allocation here (after the guards)
5525     _gvn.hash_delete(alloc);
5526     alloc->set_req(TypeFunc::Control, control());
5527     alloc->set_req(TypeFunc::I_O, i_o());
5528     Node *mem = reset_memory();
5529     set_all_memory(mem);
5530     alloc->set_req(TypeFunc::Memory, mem);
5531     set_control(init->proj_out_or_null(TypeFunc::Control));
5532     set_i_o(callprojs.fallthrough_ioproj);
5533 
5534     // Update memory as done in GraphKit::set_output_for_allocation()
5535     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5536     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5537     if (ary_type->isa_aryptr() && length_type != nullptr) {
5538       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5539     }
5540     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5541     int            elemidx  = C->get_alias_index(telemref);
5542     // Need to properly move every memory projection for the Initialize
5543 #ifdef ASSERT
5544     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5545     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5546 #endif
5547     auto move_proj = [&](ProjNode* proj) {
5548       int alias_idx = C->get_alias_index(proj->adr_type());
5549       assert(alias_idx == Compile::AliasIdxRaw ||
5550              alias_idx == elemidx ||
5551              alias_idx == mark_idx ||
5552              alias_idx == klass_idx, "should be raw memory or array element type");

5862         top_src  = src_type->isa_aryptr();
5863         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5864         src_spec = true;
5865       }
5866       if (!has_dest) {
5867         dest = maybe_cast_profiled_obj(dest, dest_k, true);
5868         dest_type  = _gvn.type(dest);
5869         top_dest  = dest_type->isa_aryptr();
5870         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5871         dest_spec = true;
5872       }
5873     }
5874   }
5875 
5876   if (has_src && has_dest && can_emit_guards) {
5877     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5878     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5879     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5880     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5881 
5882     if (src_elem == dest_elem && src_elem == T_OBJECT) {
5883       // If both arrays are object arrays then having the exact types
5884       // for both will remove the need for a subtype check at runtime
5885       // before the call and may make it possible to pick a faster copy
5886       // routine (without a subtype check on every element)
5887       // Do we have the exact type of src?
5888       bool could_have_src = src_spec;
5889       // Do we have the exact type of dest?
5890       bool could_have_dest = dest_spec;
5891       ciKlass* src_k = nullptr;
5892       ciKlass* dest_k = nullptr;
5893       if (!src_spec) {
5894         src_k = src_type->speculative_type_not_null();
5895         if (src_k != nullptr && src_k->is_array_klass()) {
5896           could_have_src = true;
5897         }
5898       }
5899       if (!dest_spec) {
5900         dest_k = dest_type->speculative_type_not_null();
5901         if (dest_k != nullptr && dest_k->is_array_klass()) {
5902           could_have_dest = true;
5903         }
5904       }
5905       if (could_have_src && could_have_dest) {
5906         // If we can have both exact types, emit the missing guards
5907         if (could_have_src && !src_spec) {
5908           src = maybe_cast_profiled_obj(src, src_k, true);


5909         }
5910         if (could_have_dest && !dest_spec) {
5911           dest = maybe_cast_profiled_obj(dest, dest_k, true);


5912         }
5913       }
5914     }
5915   }
5916 
5917   ciMethod* trap_method = method();
5918   int trap_bci = bci();
5919   if (saved_jvms_before_guards != nullptr) {
5920     trap_method = alloc->jvms()->method();
5921     trap_bci = alloc->jvms()->bci();
5922   }
5923 
5924   bool negative_length_guard_generated = false;
5925 
5926   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5927       can_emit_guards &&
5928       !src->is_top() && !dest->is_top()) {
5929     // validate arguments: enables transformation the ArrayCopyNode
5930     validated = true;
5931 
5932     RegionNode* slow_region = new RegionNode(1);
5933     record_for_igvn(slow_region);
5934 
5935     // (1) src and dest are arrays.
5936     generate_non_array_guard(load_object_klass(src), slow_region, &src);
5937     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
5938 
5939     // (2) src and dest arrays must have elements of the same BasicType
5940     // done at macro expansion or at Ideal transformation time
5941 
5942     // (4) src_offset must not be negative.
5943     generate_negative_guard(src_offset, slow_region);
5944 
5945     // (5) dest_offset must not be negative.
5946     generate_negative_guard(dest_offset, slow_region);
5947 
5948     // (7) src_offset + length must not exceed length of src.
5949     generate_limit_guard(src_offset, length,
5950                          load_array_length(src),
5951                          slow_region);
5952 
5953     // (8) dest_offset + length must not exceed length of dest.
5954     generate_limit_guard(dest_offset, length,
5955                          load_array_length(dest),
5956                          slow_region);
5957 
5958     // (6) length must not be negative.
5959     // This is also checked in generate_arraycopy() during macro expansion, but
5960     // we also have to check it here for the case where the ArrayCopyNode will
5961     // be eliminated by Escape Analysis.
5962     if (EliminateAllocations) {
5963       generate_negative_guard(length, slow_region);
5964       negative_length_guard_generated = true;
5965     }
5966 
5967     // (9) each element of an oop array must be assignable
5968     Node* dest_klass = load_object_klass(dest);

5969     if (src != dest) {

5970       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
5971 
5972       if (not_subtype_ctrl != top()) {
5973         PreserveJVMState pjvms(this);
5974         set_control(not_subtype_ctrl);
5975         uncommon_trap(Deoptimization::Reason_intrinsic,
5976                       Deoptimization::Action_make_not_entrant);
5977         assert(stopped(), "Should be stopped");
5978       }
5979     }




























5980     {
5981       PreserveJVMState pjvms(this);
5982       set_control(_gvn.transform(slow_region));
5983       uncommon_trap(Deoptimization::Reason_intrinsic,
5984                     Deoptimization::Action_make_not_entrant);
5985       assert(stopped(), "Should be stopped");
5986     }
5987 
5988     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
5989     const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();








5990     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
5991     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
5992   }
5993 
5994   if (stopped()) {
5995     return true;
5996   }
5997 



5998   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
5999                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6000                                           // so the compiler has a chance to eliminate them: during macro expansion,
6001                                           // we have to set their control (CastPP nodes are eliminated).
6002                                           load_object_klass(src), load_object_klass(dest),
6003                                           load_array_length(src), load_array_length(dest));
6004 
6005   ac->set_arraycopy(validated);
6006 
6007   Node* n = _gvn.transform(ac);
6008   if (n == ac) {
6009     ac->connect_outputs(this);
6010   } else {
6011     assert(validated, "shouldn't transform if all arguments not validated");
6012     set_all_memory(n);
6013   }
6014   clear_upper_avx();
6015 
6016 
6017   return true;
6018 }
6019 
6020 
6021 // Helper function which determines if an arraycopy immediately follows
6022 // an allocation, with no intervening tests or other escapes for the object.

   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 "asm/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.

 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);

 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);

 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:

2288     case vmIntrinsics::_remainderUnsigned_l: {
2289       zero_check_long(argument(2));
2290       // Compile-time detect of null-exception
2291       if (stopped()) {
2292         return true; // keep the graph constructed so far
2293       }
2294       n = new UModLNode(control(), argument(0), argument(2));
2295       break;
2296     }
2297     default:  fatal_unexpected_iid(id);  break;
2298   }
2299   set_result(_gvn.transform(n));
2300   return true;
2301 }
2302 
2303 //----------------------------inline_unsafe_access----------------------------
2304 
2305 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2306   // Attempt to infer a sharper value type from the offset and base type.
2307   ciKlass* sharpened_klass = nullptr;
2308   bool null_free = false;
2309 
2310   // See if it is an instance field, with an object type.
2311   if (alias_type->field() != nullptr) {
2312     if (alias_type->field()->type()->is_klass()) {
2313       sharpened_klass = alias_type->field()->type()->as_klass();
2314       null_free = alias_type->field()->is_null_free();
2315     }
2316   }
2317 
2318   const TypeOopPtr* result = nullptr;
2319   // See if it is a narrow oop array.
2320   if (adr_type->isa_aryptr()) {
2321     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2322       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2323       null_free = adr_type->is_aryptr()->is_null_free();
2324       if (elem_type != nullptr && elem_type->is_loaded()) {
2325         // Sharpen the value type.
2326         result = elem_type;
2327       }
2328     }
2329   }
2330 
2331   // The sharpened class might be unloaded if there is no class loader
2332   // contraint in place.
2333   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2334     // Sharpen the value type.
2335     result = TypeOopPtr::make_from_klass(sharpened_klass);
2336     if (null_free) {
2337       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2338     }
2339   }
2340   if (result != nullptr) {
2341 #ifndef PRODUCT
2342     if (C->print_intrinsics() || C->print_inlining()) {
2343       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2344       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2345     }
2346 #endif
2347   }
2348   return result;
2349 }
2350 
2351 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2352   switch (kind) {
2353       case Relaxed:
2354         return MO_UNORDERED;
2355       case Opaque:
2356         return MO_RELAXED;
2357       case Acquire:
2358         return MO_ACQUIRE;

2406 #endif // ASSERT
2407  }
2408 #endif //PRODUCT
2409 
2410   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2411 
2412   Node* receiver = argument(0);  // type: oop
2413 
2414   // Build address expression.
2415   Node* heap_base_oop = top();
2416 
2417   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2418   Node* base = argument(1);  // type: oop
2419   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2420   Node* offset = argument(2);  // type: long
2421   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2422   // to be plain byte offsets, which are also the same as those accepted
2423   // by oopDesc::field_addr.
2424   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2425          "fieldOffset must be byte-scaled");
2426 
2427   if (base->is_InlineType()) {
2428     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2429     InlineTypeNode* vt = base->as_InlineType();
2430     if (offset->is_Con()) {
2431       long off = find_long_con(offset, 0);
2432       ciInlineKlass* vk = vt->type()->inline_klass();
2433       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2434         return false;
2435       }
2436 
2437       ciField* field = vk->get_non_flat_field_by_offset(off);
2438       if (field != nullptr) {
2439         BasicType bt = type2field[field->type()->basic_type()];
2440         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2441           bt = T_OBJECT;
2442         }
2443         if (bt == type && !field->is_flat()) {
2444           Node* value = vt->field_value_by_offset(off, false);
2445           const Type* value_type = _gvn.type(value);
2446           if (value->is_InlineType()) {
2447             value = value->as_InlineType()->adjust_scalarization_depth(this);
2448           } else if (value_type->is_inlinetypeptr()) {
2449             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2450           }
2451           set_result(value);
2452           return true;
2453         }
2454       }
2455     }
2456     {
2457       // Re-execute the unsafe access if allocation triggers deoptimization.
2458       PreserveReexecuteState preexecs(this);
2459       jvms()->set_should_reexecute(true);
2460       vt = vt->buffer(this);
2461     }
2462     base = vt->get_oop();
2463   }
2464 
2465   // 32-bit machines ignore the high half!
2466   offset = ConvL2X(offset);
2467 
2468   // Save state and restore on bailout
2469   SavedState old_state(this);
2470 
2471   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2472   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2473 
2474   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2475     if (type != T_OBJECT) {
2476       decorators |= IN_NATIVE; // off-heap primitive access
2477     } else {
2478       return false; // off-heap oop accesses are not supported
2479     }
2480   } else {
2481     heap_base_oop = base; // on-heap or mixed access
2482   }
2483 
2484   // Can base be null? Otherwise, always on-heap access.

2488     decorators |= IN_HEAP;
2489   }
2490 
2491   Node* val = is_store ? argument(4) : nullptr;
2492 
2493   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2494   if (adr_type == TypePtr::NULL_PTR) {
2495     return false; // off-heap access with zero address
2496   }
2497 
2498   // Try to categorize the address.
2499   Compile::AliasType* alias_type = C->alias_type(adr_type);
2500   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2501 
2502   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2503       alias_type->adr_type() == TypeAryPtr::RANGE) {
2504     return false; // not supported
2505   }
2506 
2507   bool mismatched = false;
2508   BasicType bt = T_ILLEGAL;
2509   ciField* field = nullptr;
2510   if (adr_type->isa_instptr()) {
2511     const TypeInstPtr* instptr = adr_type->is_instptr();
2512     ciInstanceKlass* k = instptr->instance_klass();
2513     int off = instptr->offset();
2514     if (instptr->const_oop() != nullptr &&
2515         k == ciEnv::current()->Class_klass() &&
2516         instptr->offset() >= (k->size_helper() * wordSize)) {
2517       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2518       field = k->get_field_by_offset(off, true);
2519     } else {
2520       field = k->get_non_flat_field_by_offset(off);
2521     }
2522     if (field != nullptr) {
2523       bt = type2field[field->type()->basic_type()];
2524     }
2525     if (bt != alias_type->basic_type()) {
2526       // Type mismatch. Is it an access to a nested flat field?
2527       field = k->get_field_by_offset(off, false);
2528       if (field != nullptr) {
2529         bt = type2field[field->type()->basic_type()];
2530       }
2531     }
2532     assert(bt == alias_type->basic_type(), "should match");
2533   } else {
2534     bt = alias_type->basic_type();
2535   }
2536 
2537   if (bt != T_ILLEGAL) {
2538     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2539     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2540       // Alias type doesn't differentiate between byte[] and boolean[]).
2541       // Use address type to get the element type.
2542       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2543     }
2544     if (is_reference_type(bt, true)) {
2545       // accessing an array field with getReference is not a mismatch
2546       bt = T_OBJECT;
2547     }
2548     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2549       // Don't intrinsify mismatched object accesses
2550       return false;
2551     }
2552     mismatched = (bt != type);
2553   } else if (alias_type->adr_type()->isa_oopptr()) {
2554     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2555   }
2556 
2557   old_state.discard();
2558   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2559 
2560   if (mismatched) {
2561     decorators |= C2_MISMATCHED;
2562   }
2563 
2564   // First guess at the value type.
2565   const Type *value_type = Type::get_const_basic_type(type);
2566 
2567   // Figure out the memory ordering.
2568   decorators |= mo_decorator_for_access_kind(kind);
2569 
2570   if (!is_store) {
2571     if (type == T_OBJECT) {
2572       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2573       if (tjp != nullptr) {
2574         value_type = tjp;
2575       }
2576     }
2577   }
2578 
2579   receiver = null_check(receiver);
2580   if (stopped()) {
2581     return true;
2582   }
2583   // Heap pointers get a null-check from the interpreter,
2584   // as a courtesy.  However, this is not guaranteed by Unsafe,
2585   // and it is not possible to fully distinguish unintended nulls
2586   // from intended ones in this API.
2587 
2588   if (!is_store) {
2589     Node* p = nullptr;
2590     // Try to constant fold a load from a constant field
2591 
2592     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2593       // final or stable field
2594       p = make_constant_from_field(field, heap_base_oop);
2595     }
2596 
2597     if (p == nullptr) { // Could not constant fold the load
2598       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2599       const TypeOopPtr* ptr = value_type->make_oopptr();
2600       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2601         // Load a non-flattened inline type from memory
2602         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2603       }
2604       // Normalize the value returned by getBoolean in the following cases
2605       if (type == T_BOOLEAN &&
2606           (mismatched ||
2607            heap_base_oop == top() ||                  // - heap_base_oop is null or
2608            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2609                                                       //   and the unsafe access is made to large offset
2610                                                       //   (i.e., larger than the maximum offset necessary for any
2611                                                       //   field access)
2612             ) {
2613           IdealKit ideal = IdealKit(this);
2614 #define __ ideal.
2615           IdealVariable normalized_result(ideal);
2616           __ declarations_done();
2617           __ set(normalized_result, p);
2618           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2619           __ set(normalized_result, ideal.ConI(1));
2620           ideal.end_if();
2621           final_sync(ideal);
2622           p = __ value(normalized_result);
2623 #undef __

2627       p = gvn().transform(new CastP2XNode(nullptr, p));
2628       p = ConvX2UL(p);
2629     }
2630     // The load node has the control of the preceding MemBarCPUOrder.  All
2631     // following nodes will have the control of the MemBarCPUOrder inserted at
2632     // the end of this method.  So, pushing the load onto the stack at a later
2633     // point is fine.
2634     set_result(p);
2635   } else {
2636     if (bt == T_ADDRESS) {
2637       // Repackage the long as a pointer.
2638       val = ConvL2X(val);
2639       val = gvn().transform(new CastX2PNode(val));
2640     }
2641     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2642   }
2643 
2644   return true;
2645 }
2646 
2647 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2648 #ifdef ASSERT
2649   {
2650     ResourceMark rm;
2651     // Check the signatures.
2652     ciSignature* sig = callee()->signature();
2653     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2654     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2655     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2656     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2657     if (is_store) {
2658       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2659       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2660       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2661     } else {
2662       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2663       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2664     }
2665  }
2666 #endif // ASSERT
2667 
2668   assert(kind == Relaxed, "Only plain accesses for now");
2669   if (callee()->is_static()) {
2670     // caller must have the capability!
2671     return false;
2672   }
2673   C->set_has_unsafe_access(true);
2674 
2675   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2676   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2677     // parameter valueType is not a constant
2678     return false;
2679   }
2680   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2681   if (!mirror_type->is_inlinetype()) {
2682     // Dead code
2683     return false;
2684   }
2685   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2686 
2687   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2688   if (layout_type == nullptr || !layout_type->is_con()) {
2689     // parameter layoutKind is not a constant
2690     return false;
2691   }
2692   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2693          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2694          "invalid layoutKind %d", layout_type->get_con());
2695   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2696   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2697          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2698          "unexpected layoutKind %d", layout_type->get_con());
2699 
2700   null_check(argument(0));
2701   if (stopped()) {
2702     return true;
2703   }
2704 
2705   Node* base = must_be_not_null(argument(1), true);
2706   Node* offset = argument(2);
2707   const Type* base_type = _gvn.type(base);
2708 
2709   Node* ptr;
2710   bool immutable_memory = false;
2711   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2712   if (base_type->isa_instptr()) {
2713     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2714     if (offset_type == nullptr || !offset_type->is_con()) {
2715       // Offset into a non-array should be a constant
2716       decorators |= C2_MISMATCHED;
2717     } else {
2718       int offset_con = checked_cast<int>(offset_type->get_con());
2719       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2720       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2721       if (field == nullptr) {
2722         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2723         decorators |= C2_MISMATCHED;
2724       } else {
2725         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2726                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2727         immutable_memory = field->is_strict() && field->is_final();
2728 
2729         if (base->is_InlineType()) {
2730           assert(!is_store, "Cannot store into a non-larval value object");
2731           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2732           return true;
2733         }
2734       }
2735     }
2736 
2737     if (base->is_InlineType()) {
2738       assert(!is_store, "Cannot store into a non-larval value object");
2739       base = base->as_InlineType()->buffer(this, true);
2740     }
2741     ptr = basic_plus_adr(base, ConvL2X(offset));
2742   } else if (base_type->isa_aryptr()) {
2743     decorators |= IS_ARRAY;
2744     if (layout == LayoutKind::REFERENCE) {
2745       if (!base_type->is_aryptr()->is_not_flat()) {
2746         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2747         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2748         replace_in_map(base, new_base);
2749         base = new_base;
2750       }
2751       ptr = basic_plus_adr(base, ConvL2X(offset));
2752     } else {
2753       if (UseArrayFlattening) {
2754         // Flat array must have an exact type
2755         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2756         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2757         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2758         replace_in_map(base, new_base);
2759         base = new_base;
2760         ptr = basic_plus_adr(base, ConvL2X(offset));
2761         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2762         if (ptr_type->field_offset().get() != 0) {
2763           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2764         }
2765       } else {
2766         uncommon_trap(Deoptimization::Reason_intrinsic,
2767                       Deoptimization::Action_none);
2768         return true;
2769       }
2770     }
2771   } else {
2772     decorators |= C2_MISMATCHED;
2773     ptr = basic_plus_adr(base, ConvL2X(offset));
2774   }
2775 
2776   if (is_store) {
2777     Node* value = argument(6);
2778     const Type* value_type = _gvn.type(value);
2779     if (!value_type->is_inlinetypeptr()) {
2780       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2781       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2782       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2783       replace_in_map(value, new_value);
2784       value = new_value;
2785     }
2786 
2787     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2788     if (layout == LayoutKind::REFERENCE) {
2789       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2790       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2791     } else {
2792       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2793       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2794       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2795     }
2796 
2797     return true;
2798   } else {
2799     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2800     InlineTypeNode* result;
2801     if (layout == LayoutKind::REFERENCE) {
2802       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2803       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2804       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2805     } else {
2806       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2807       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2808       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2809     }
2810 
2811     set_result(result);
2812     return true;
2813   }
2814 }
2815 
2816 //----------------------------inline_unsafe_load_store----------------------------
2817 // This method serves a couple of different customers (depending on LoadStoreKind):
2818 //
2819 // LS_cmp_swap:
2820 //
2821 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2822 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2823 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2824 //
2825 // LS_cmp_swap_weak:
2826 //
2827 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2828 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2829 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2830 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2831 //
2832 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2833 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2834 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2835 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);

2998     }
2999     case LS_cmp_swap:
3000     case LS_cmp_swap_weak:
3001     case LS_get_add:
3002       break;
3003     default:
3004       ShouldNotReachHere();
3005   }
3006 
3007   // Null check receiver.
3008   receiver = null_check(receiver);
3009   if (stopped()) {
3010     return true;
3011   }
3012 
3013   int alias_idx = C->get_alias_index(adr_type);
3014 
3015   if (is_reference_type(type)) {
3016     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3017 
3018     if (oldval != nullptr && oldval->is_InlineType()) {
3019       // Re-execute the unsafe access if allocation triggers deoptimization.
3020       PreserveReexecuteState preexecs(this);
3021       jvms()->set_should_reexecute(true);
3022       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3023     }
3024     if (newval != nullptr && newval->is_InlineType()) {
3025       // Re-execute the unsafe access if allocation triggers deoptimization.
3026       PreserveReexecuteState preexecs(this);
3027       jvms()->set_should_reexecute(true);
3028       newval = newval->as_InlineType()->buffer(this)->get_oop();
3029     }
3030 
3031     // Transformation of a value which could be null pointer (CastPP #null)
3032     // could be delayed during Parse (for example, in adjust_map_after_if()).
3033     // Execute transformation here to avoid barrier generation in such case.
3034     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3035       newval = _gvn.makecon(TypePtr::NULL_PTR);
3036 
3037     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3038       // Refine the value to a null constant, when it is known to be null
3039       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3040     }
3041   }
3042 
3043   Node* result = nullptr;
3044   switch (kind) {
3045     case LS_cmp_exchange: {
3046       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3047                                             oldval, newval, value_type, type, decorators);
3048       break;
3049     }
3050     case LS_cmp_swap_weak:

3079   insert_mem_bar(Op_MemBarCPUOrder);
3080   switch(id) {
3081     case vmIntrinsics::_loadFence:
3082       insert_mem_bar(Op_LoadFence);
3083       return true;
3084     case vmIntrinsics::_storeFence:
3085       insert_mem_bar(Op_StoreFence);
3086       return true;
3087     case vmIntrinsics::_storeStoreFence:
3088       insert_mem_bar(Op_StoreStoreFence);
3089       return true;
3090     case vmIntrinsics::_fullFence:
3091       insert_mem_bar(Op_MemBarFull);
3092       return true;
3093     default:
3094       fatal_unexpected_iid(id);
3095       return false;
3096   }
3097 }
3098 
3099 // private native int arrayInstanceBaseOffset0(Object[] array);
3100 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3101   Node* array = argument(1);
3102   Node* klass_node = load_object_klass(array);
3103 
3104   jint  layout_con = Klass::_lh_neutral_value;
3105   Node* layout_val = get_layout_helper(klass_node, layout_con);
3106   int   layout_is_con = (layout_val == nullptr);
3107 
3108   Node* header_size = nullptr;
3109   if (layout_is_con) {
3110     int hsize = Klass::layout_helper_header_size(layout_con);
3111     header_size = intcon(hsize);
3112   } else {
3113     Node* hss = intcon(Klass::_lh_header_size_shift);
3114     Node* hsm = intcon(Klass::_lh_header_size_mask);
3115     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3116     header_size = _gvn.transform(new AndINode(header_size, hsm));
3117   }
3118   set_result(header_size);
3119   return true;
3120 }
3121 
3122 // private native int arrayInstanceIndexScale0(Object[] array);
3123 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3124   Node* array = argument(1);
3125   Node* klass_node = load_object_klass(array);
3126 
3127   jint  layout_con = Klass::_lh_neutral_value;
3128   Node* layout_val = get_layout_helper(klass_node, layout_con);
3129   int   layout_is_con = (layout_val == nullptr);
3130 
3131   Node* element_size = nullptr;
3132   if (layout_is_con) {
3133     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3134     int elem_size = 1 << log_element_size;
3135     element_size = intcon(elem_size);
3136   } else {
3137     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3138     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3139     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3140     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3141     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3142   }
3143   set_result(element_size);
3144   return true;
3145 }
3146 
3147 // private native int arrayLayout0(Object[] array);
3148 bool LibraryCallKit::inline_arrayLayout() {
3149   RegionNode* region = new RegionNode(2);
3150   Node* phi = new PhiNode(region, TypeInt::POS);
3151 
3152   Node* array = argument(1);
3153   Node* klass_node = load_object_klass(array);
3154   generate_refArray_guard(klass_node, region);
3155   if (region->req() == 3) {
3156     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3157   }
3158 
3159   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3160   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3161   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3162 
3163   region->init_req(1, control());
3164   phi->init_req(1, layout_kind);
3165 
3166   set_control(_gvn.transform(region));
3167   set_result(_gvn.transform(phi));
3168   return true;
3169 }
3170 
3171 // private native int[] getFieldMap0(Class <?> c);
3172 //   int offset = c._klass._acmp_maps_offset;
3173 //   return (int[])c.obj_field(offset);
3174 bool LibraryCallKit::inline_getFieldMap() {
3175   Node* mirror = argument(1);
3176   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3177 
3178   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3179   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3180   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3181   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3182 
3183   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3184   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3185   // TODO 8350865 Remove this
3186   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3187   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3188 
3189   set_result(map);
3190   return true;
3191 }
3192 
3193 bool LibraryCallKit::inline_onspinwait() {
3194   insert_mem_bar(Op_OnSpinWait);
3195   return true;
3196 }
3197 
3198 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3199   if (!kls->is_Con()) {
3200     return true;
3201   }
3202   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3203   if (klsptr == nullptr) {
3204     return true;
3205   }
3206   ciInstanceKlass* ik = klsptr->instance_klass();
3207   // don't need a guard for a klass that is already initialized
3208   return !ik->is_initialized();
3209 }
3210 
3211 //----------------------------inline_unsafe_writeback0-------------------------
3212 // public native void Unsafe.writeback0(long address)

3291                     Deoptimization::Action_make_not_entrant);
3292     }
3293     if (stopped()) {
3294       return true;
3295     }
3296 #endif //INCLUDE_JVMTI
3297 
3298   Node* test = nullptr;
3299   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3300     // Note:  The argument might still be an illegal value like
3301     // Serializable.class or Object[].class.   The runtime will handle it.
3302     // But we must make an explicit check for initialization.
3303     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3304     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3305     // can generate code to load it as unsigned byte.
3306     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3307     Node* bits = intcon(InstanceKlass::fully_initialized);
3308     test = _gvn.transform(new SubINode(inst, bits));
3309     // The 'test' is non-zero if we need to take a slow path.
3310   }

3311   Node* obj = new_instance(kls, test);
3312   set_result(obj);
3313   return true;
3314 }
3315 
3316 //------------------------inline_native_time_funcs--------------
3317 // inline code for System.currentTimeMillis() and System.nanoTime()
3318 // these have the same type and signature
3319 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3320   const TypeFunc* tf = OptoRuntime::void_long_Type();
3321   const TypePtr* no_memory_effects = nullptr;
3322   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3323   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3324 #ifdef ASSERT
3325   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3326   assert(value_top == top(), "second value must be top");
3327 #endif
3328   set_result(value);
3329   return true;
3330 }

4106   Node* arr = argument(1);
4107   Node* thread = _gvn.transform(new ThreadLocalNode());
4108   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4109   Node* thread_obj_handle
4110     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4111   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4112   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4113 
4114   // Change the _monitor_owner_id of the JavaThread
4115   Node* tid = load_field_from_object(arr, "tid", "J");
4116   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4117   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4118 
4119   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4120   return true;
4121 }
4122 
4123 const Type* LibraryCallKit::scopedValueCache_type() {
4124   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4125   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4126   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4127 
4128   // Because we create the scopedValue cache lazily we have to make the
4129   // type of the result BotPTR.
4130   bool xk = etype->klass_is_exact();
4131   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4132   return objects_type;
4133 }
4134 
4135 Node* LibraryCallKit::scopedValueCache_helper() {
4136   Node* thread = _gvn.transform(new ThreadLocalNode());
4137   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4138   // We cannot use immutable_memory() because we might flip onto a
4139   // different carrier thread, at which point we'll need to use that
4140   // carrier thread's cache.
4141   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4142   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4143   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4144 }
4145 
4146 //------------------------inline_native_scopedValueCache------------------
4147 bool LibraryCallKit::inline_native_scopedValueCache() {
4148   Node* cache_obj_handle = scopedValueCache_helper();
4149   const Type* objects_type = scopedValueCache_type();
4150   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4151 

4287   }
4288   return kls;
4289 }
4290 
4291 //--------------------(inline_native_Class_query helpers)---------------------
4292 // Use this for JVM_ACC_INTERFACE.
4293 // Fall through if (mods & mask) == bits, take the guard otherwise.
4294 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4295                                                  ByteSize offset, const Type* type, BasicType bt) {
4296   // Branch around if the given klass has the given modifier bit set.
4297   // Like generate_guard, adds a new path onto the region.
4298   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4299   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4300   Node* mask = intcon(modifier_mask);
4301   Node* bits = intcon(modifier_bits);
4302   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4303   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4304   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4305   return generate_fair_guard(bol, region);
4306 }
4307 
4308 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4309   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4310                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4311 }
4312 
4313 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4314 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4315   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4316                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4317 }
4318 
4319 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4320   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4321 }
4322 
4323 //-------------------------inline_native_Class_query-------------------
4324 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4325   const Type* return_type = TypeInt::BOOL;
4326   Node* prim_return_value = top();  // what happens if it's a primitive class?
4327   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);

4413 
4414 
4415   case vmIntrinsics::_getSuperclass:
4416     // The rules here are somewhat unfortunate, but we can still do better
4417     // with random logic than with a JNI call.
4418     // Interfaces store null or Object as _super, but must report null.
4419     // Arrays store an intermediate super as _super, but must report Object.
4420     // Other types can report the actual _super.
4421     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4422     if (generate_array_guard(kls, region) != nullptr) {
4423       // A guard was added.  If the guard is taken, it was an array.
4424       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4425     }
4426     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4427     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4428     if (generate_interface_guard(kls, region) != nullptr) {
4429       // A guard was added.  If the guard is taken, it was an interface.
4430       phi->add_req(null());
4431     }
4432     // If we fall through, it's a plain class.  Get its _super.









4433     if (!stopped()) {
4434       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4435       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4436       null_ctl = top();
4437       kls = null_check_oop(kls, &null_ctl);
4438       if (null_ctl != top()) {
4439         // If the guard is taken, Object.superClass is null (both klass and mirror).
4440         region->add_req(null_ctl);
4441         phi   ->add_req(null());
4442       }
4443       if (!stopped()) {
4444         query_value = load_mirror_from_klass(kls);
4445       }
4446     }
4447     break;
4448 
4449   default:
4450     fatal_unexpected_iid(id);
4451     break;
4452   }
4453 
4454   // Fall-through is the normal case of a query to a real class.
4455   phi->init_req(1, query_value);
4456   region->init_req(1, control());
4457 
4458   C->set_has_split_ifs(true); // Has chance for split-if optimization
4459   set_result(region, phi);
4460   return true;
4461 }
4462 
4463 
4464 //-------------------------inline_Class_cast-------------------
4465 bool LibraryCallKit::inline_Class_cast() {
4466   Node* mirror = argument(0); // Class
4467   Node* obj    = argument(1);
4468   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4469   if (mirror_con == nullptr) {
4470     return false;  // dead path (mirror->is_top()).
4471   }
4472   if (obj == nullptr || obj->is_top()) {
4473     return false;  // dead path
4474   }
4475   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4476 
4477   // First, see if Class.cast() can be folded statically.
4478   // java_mirror_type() returns non-null for compile-time Class constants.
4479   ciType* tm = mirror_con->java_mirror_type();
4480   if (tm != nullptr && tm->is_klass() &&
4481       tp != nullptr) {
4482     if (!tp->is_loaded()) {
4483       // Don't use intrinsic when class is not loaded.
4484       return false;
4485     } else {
4486       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4487       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4488       if (static_res == Compile::SSC_always_true) {
4489         // isInstance() is true - fold the code.
4490         set_result(obj);
4491         return true;
4492       } else if (static_res == Compile::SSC_always_false) {
4493         // Don't use intrinsic, have to throw ClassCastException.
4494         // If the reference is null, the non-intrinsic bytecode will
4495         // be optimized appropriately.
4496         return false;
4497       }
4498     }
4499   }
4500 
4501   // Bailout intrinsic and do normal inlining if exception path is frequent.
4502   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4503     return false;
4504   }
4505 
4506   // Generate dynamic checks.
4507   // Class.cast() is java implementation of _checkcast bytecode.
4508   // Do checkcast (Parse::do_checkcast()) optimizations here.
4509 
4510   mirror = null_check(mirror);
4511   // If mirror is dead, only null-path is taken.
4512   if (stopped()) {
4513     return true;
4514   }
4515 
4516   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4517   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4518   RegionNode* region = new RegionNode(PATH_LIMIT);
4519   record_for_igvn(region);
4520 
4521   // Now load the mirror's klass metaobject, and null-check it.
4522   // If kls is null, we have a primitive mirror and
4523   // nothing is an instance of a primitive type.
4524   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4525 
4526   Node* res = top();
4527   Node* io = i_o();
4528   Node* mem = merged_memory();
4529   SafePointNode* new_cast_failure_map = nullptr;
4530 
4531   if (!stopped()) {
4532 
4533     Node* bad_type_ctrl = top();
4534     // Do checkcast optimizations.
4535     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4536     region->init_req(_bad_type_path, bad_type_ctrl);
4537   }
4538   if (region->in(_prim_path) != top() ||
4539       region->in(_bad_type_path) != top() ||
4540       region->in(_npe_path) != top()) {
4541     // Let Interpreter throw ClassCastException.
4542     PreserveJVMState pjvms(this);
4543     if (new_cast_failure_map != nullptr) {
4544       // The current map on the success path could have been modified. Use the dedicated failure path map.
4545       set_map(new_cast_failure_map);
4546     }
4547     set_control(_gvn.transform(region));
4548     // Set IO and memory because gen_checkcast may override them when buffering inline types
4549     set_i_o(io);
4550     set_all_memory(mem);
4551     uncommon_trap(Deoptimization::Reason_intrinsic,
4552                   Deoptimization::Action_maybe_recompile);
4553   }
4554   if (!stopped()) {
4555     set_result(res);
4556   }
4557   return true;
4558 }
4559 
4560 
4561 //--------------------------inline_native_subtype_check------------------------
4562 // This intrinsic takes the JNI calls out of the heart of
4563 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4564 bool LibraryCallKit::inline_native_subtype_check() {
4565   // Pull both arguments off the stack.
4566   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4567   args[0] = argument(0);
4568   args[1] = argument(1);
4569   Node* klasses[2];             // corresponding Klasses: superk, subk
4570   klasses[0] = klasses[1] = top();
4571 
4572   enum {
4573     // A full decision tree on {superc is prim, subc is prim}:
4574     _prim_0_path = 1,           // {P,N} => false
4575                                 // {P,P} & superc!=subc => false
4576     _prim_same_path,            // {P,P} & superc==subc => true
4577     _prim_1_path,               // {N,P} => false
4578     _ref_subtype_path,          // {N,N} & subtype check wins => true
4579     _both_ref_path,             // {N,N} & subtype check loses => false
4580     PATH_LIMIT
4581   };
4582 
4583   RegionNode* region = new RegionNode(PATH_LIMIT);
4584   RegionNode* prim_region = new RegionNode(2);
4585   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4586   record_for_igvn(region);
4587   record_for_igvn(prim_region);
4588 
4589   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4590   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4591   int class_klass_offset = java_lang_Class::klass_offset();
4592 
4593   // First null-check both mirrors and load each mirror's klass metaobject.
4594   int which_arg;
4595   for (which_arg = 0; which_arg <= 1; which_arg++) {
4596     Node* arg = args[which_arg];
4597     arg = null_check(arg);
4598     if (stopped())  break;
4599     args[which_arg] = arg;
4600 
4601     Node* p = basic_plus_adr(arg, class_klass_offset);
4602     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4603     klasses[which_arg] = _gvn.transform(kls);
4604   }
4605 
4606   // Having loaded both klasses, test each for null.
4607   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4608   for (which_arg = 0; which_arg <= 1; which_arg++) {
4609     Node* kls = klasses[which_arg];
4610     Node* null_ctl = top();
4611     kls = null_check_oop(kls, &null_ctl, never_see_null);
4612     if (which_arg == 0) {
4613       prim_region->init_req(1, null_ctl);
4614     } else {
4615       region->init_req(_prim_1_path, null_ctl);
4616     }
4617     if (stopped())  break;
4618     klasses[which_arg] = kls;
4619   }
4620 
4621   if (!stopped()) {
4622     // now we have two reference types, in klasses[0..1]
4623     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4624     Node* superk = klasses[0];  // the receiver
4625     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));

4626     region->set_req(_ref_subtype_path, control());
4627   }
4628 
4629   // If both operands are primitive (both klasses null), then
4630   // we must return true when they are identical primitives.
4631   // It is convenient to test this after the first null klass check.
4632   // This path is also used if superc is a value mirror.
4633   set_control(_gvn.transform(prim_region));
4634   if (!stopped()) {
4635     // Since superc is primitive, make a guard for the superc==subc case.
4636     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4637     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4638     generate_fair_guard(bol_eq, region);
4639     if (region->req() == PATH_LIMIT+1) {
4640       // A guard was added.  If the added guard is taken, superc==subc.
4641       region->swap_edges(PATH_LIMIT, _prim_same_path);
4642       region->del_req(PATH_LIMIT);
4643     }
4644     region->set_req(_prim_0_path, control()); // Not equal after all.
4645   }
4646 
4647   // these are the only paths that produce 'true':
4648   phi->set_req(_prim_same_path,   intcon(1));
4649   phi->set_req(_ref_subtype_path, intcon(1));
4650 
4651   // pull together the cases:
4652   assert(region->req() == PATH_LIMIT, "sane region");
4653   for (uint i = 1; i < region->req(); i++) {
4654     Node* ctl = region->in(i);
4655     if (ctl == nullptr || ctl == top()) {
4656       region->set_req(i, top());
4657       phi   ->set_req(i, top());
4658     } else if (phi->in(i) == nullptr) {
4659       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4660     }
4661   }
4662 
4663   set_control(_gvn.transform(region));
4664   set_result(_gvn.transform(phi));
4665   return true;
4666 }
4667 
4668 //---------------------generate_array_guard_common------------------------
4669 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {

4670 
4671   if (stopped()) {
4672     return nullptr;
4673   }
4674 









4675   // Like generate_guard, adds a new path onto the region.
4676   jint  layout_con = 0;
4677   Node* layout_val = get_layout_helper(kls, layout_con);
4678   if (layout_val == nullptr) {
4679     bool query = 0;
4680     switch(kind) {
4681       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4682       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4683       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4684       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4685       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4686       default:
4687         ShouldNotReachHere();
4688     }
4689     if (!query) {
4690       return nullptr;                       // never a branch
4691     } else {                             // always a branch
4692       Node* always_branch = control();
4693       if (region != nullptr)
4694         region->add_req(always_branch);
4695       set_control(top());
4696       return always_branch;
4697     }
4698   }
4699   unsigned int value = 0;
4700   BoolTest::mask btest = BoolTest::illegal;
4701   switch(kind) {
4702     case RefArray:
4703     case NonRefArray: {
4704       value = Klass::_lh_array_tag_ref_value;
4705       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4706       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4707       break;
4708     }
4709     case TypeArray: {
4710       value = Klass::_lh_array_tag_type_value;
4711       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4712       btest = BoolTest::eq;
4713       break;
4714     }
4715     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4716     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4717     default:
4718       ShouldNotReachHere();
4719   }
4720   // Now test the correct condition.
4721   jint nval = (jint)value;



4722   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));



4723   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4724   Node* ctrl = generate_fair_guard(bol, region);
4725   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4726   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4727     // Keep track of the fact that 'obj' is an array to prevent
4728     // array specific accesses from floating above the guard.
4729     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4730   }
4731   return ctrl;
4732 }
4733 
4734 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4735 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4736 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4737 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4738   assert(null_free || atomic, "nullable implies atomic");
4739   Node* componentType = argument(0);
4740   Node* length = argument(1);
4741   Node* init_val = null_free ? argument(2) : nullptr;
4742 
4743   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4744   if (tp != nullptr) {
4745     ciInstanceKlass* ik = tp->instance_klass();
4746     if (ik == C->env()->Class_klass()) {
4747       ciType* t = tp->java_mirror_type();
4748       if (t != nullptr && t->is_inlinetype()) {
4749 
4750         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4751         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4752 
4753         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4754         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4755           return false;
4756         }
4757 
4758         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4759           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4760           if (null_free) {
4761             if (init_val->is_InlineType()) {
4762               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4763                 // Zeroing is enough because the init value is the all-zero value
4764                 init_val = nullptr;
4765               } else {
4766                 init_val = init_val->as_InlineType()->buffer(this);
4767               }
4768             }
4769             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4770             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4771             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4772             // remove the check init_val->is_InlineType().
4773           }
4774           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4775           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4776           assert(arytype->is_null_free() == null_free, "inconsistency");
4777           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4778           set_result(obj);
4779           return true;
4780         }
4781       }
4782     }
4783   }
4784   return false;
4785 }
4786 
4787 // public static native boolean ValueClass::isFlatArray(Object array);
4788 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4789 // public static native boolean ValueClass::isAtomicArray(Object array);
4790 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4791   Node* array = argument(0);
4792 
4793   Node* bol;
4794   switch(check) {
4795     case IsFlat:
4796       // TODO 8350865 Use the object version here instead of loading the klass
4797       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4798       bol = flat_array_test(load_object_klass(array));
4799       break;
4800     case IsNullRestricted:
4801       bol = null_free_array_test(array);
4802       break;
4803     case IsAtomic:
4804       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4805       // Enable TestIntrinsics::test87/88 once this is implemented
4806       // bol = null_free_atomic_array_test
4807       return false;
4808     default:
4809       ShouldNotReachHere();
4810   }
4811 
4812   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4813   set_result(res);
4814   return true;
4815 }
4816 
4817 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4818 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4819 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4820   RegionNode* region = new RegionNode(2);
4821   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4822 
4823   if (type_array_guard) {
4824     generate_typeArray_guard(klass_node, region);
4825     if (region->req() == 3) {
4826       phi->add_req(klass_node);
4827     }
4828   }
4829   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4830   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4831 
4832   // Can be null if not initialized yet, just deopt
4833   Node* null_ctl = top();
4834   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4835 
4836   region->init_req(1, control());
4837   phi->init_req(1, refined_klass);
4838 
4839   set_control(_gvn.transform(region));
4840   return _gvn.transform(phi);
4841 }
4842 
4843 // Load the non-refined array klass from an ObjArrayKlass.
4844 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4845   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4846   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4847     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4848   }
4849 
4850   RegionNode* region = new RegionNode(2);
4851   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4852 
4853   generate_typeArray_guard(klass_node, region);
4854   if (region->req() == 3) {
4855     phi->add_req(klass_node);
4856   }
4857   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4858   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4859 
4860   region->init_req(1, control());
4861   phi->init_req(1, super_klass);
4862 
4863   set_control(_gvn.transform(region));
4864   return _gvn.transform(phi);
4865 }
4866 
4867 //-----------------------inline_native_newArray--------------------------
4868 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4869 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4870 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4871   Node* mirror;
4872   Node* count_val;
4873   if (uninitialized) {
4874     null_check_receiver();
4875     mirror    = argument(1);
4876     count_val = argument(2);
4877   } else {
4878     mirror    = argument(0);
4879     count_val = argument(1);
4880   }
4881 
4882   mirror = null_check(mirror);
4883   // If mirror or obj is dead, only null-path is taken.
4884   if (stopped())  return true;
4885 
4886   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4887   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4888   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);

4906     CallJavaNode* slow_call = nullptr;
4907     if (uninitialized) {
4908       // Generate optimized virtual call (holder class 'Unsafe' is final)
4909       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4910     } else {
4911       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4912     }
4913     Node* slow_result = set_results_for_java_call(slow_call);
4914     // this->control() comes from set_results_for_java_call
4915     result_reg->set_req(_slow_path, control());
4916     result_val->set_req(_slow_path, slow_result);
4917     result_io ->set_req(_slow_path, i_o());
4918     result_mem->set_req(_slow_path, reset_memory());
4919   }
4920 
4921   set_control(normal_ctl);
4922   if (!stopped()) {
4923     // Normal case:  The array type has been cached in the java.lang.Class.
4924     // The following call works fine even if the array type is polymorphic.
4925     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4926 
4927     klass_node = load_default_refined_array_klass(klass_node);
4928 
4929     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4930     result_reg->init_req(_normal_path, control());
4931     result_val->init_req(_normal_path, obj);
4932     result_io ->init_req(_normal_path, i_o());
4933     result_mem->init_req(_normal_path, reset_memory());
4934 
4935     if (uninitialized) {
4936       // Mark the allocation so that zeroing is skipped
4937       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4938       alloc->maybe_set_complete(&_gvn);
4939     }
4940   }
4941 
4942   // Return the combined state.
4943   set_i_o(        _gvn.transform(result_io)  );
4944   set_all_memory( _gvn.transform(result_mem));
4945 
4946   C->set_has_split_ifs(true); // Has chance for split-if optimization
4947   set_result(result_reg, result_val);
4948   return true;

4997   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4998   { PreserveReexecuteState preexecs(this);
4999     jvms()->set_should_reexecute(true);
5000 
5001     array_type_mirror = null_check(array_type_mirror);
5002     original          = null_check(original);
5003 
5004     // Check if a null path was taken unconditionally.
5005     if (stopped())  return true;
5006 
5007     Node* orig_length = load_array_length(original);
5008 
5009     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5010     klass_node = null_check(klass_node);
5011 
5012     RegionNode* bailout = new RegionNode(1);
5013     record_for_igvn(bailout);
5014 
5015     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5016     // Bail out if that is so.
5017     // Inline type array may have object field that would require a
5018     // write barrier. Conservatively, go to slow path.
5019     // TODO 8251971: Optimize for the case when flat src/dst are later found
5020     // to not contain oops (i.e., move this check to the macro expansion phase).
5021     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5022     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5023     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5024     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5025                         // Can src array be flat and contain oops?
5026                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5027                         // Can dest array be flat and contain oops?
5028                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5029     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5030 
5031     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5032 
5033     if (not_objArray != nullptr) {
5034       // Improve the klass node's type from the new optimistic assumption:
5035       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5036       bool not_flat = !UseArrayFlattening;
5037       bool not_null_free = !Arguments::is_valhalla_enabled();
5038       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5039       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5040       refined_klass_node = _gvn.transform(cast);
5041     }
5042 
5043     // Bail out if either start or end is negative.
5044     generate_negative_guard(start, bailout, &start);
5045     generate_negative_guard(end,   bailout, &end);
5046 
5047     Node* length = end;
5048     if (_gvn.type(start) != TypeInt::ZERO) {
5049       length = _gvn.transform(new SubINode(end, start));
5050     }
5051 
5052     // Bail out if length is negative (i.e., if start > end).
5053     // Without this the new_array would throw
5054     // NegativeArraySizeException but IllegalArgumentException is what
5055     // should be thrown
5056     generate_negative_guard(length, bailout, &length);
5057 
5058     // Handle inline type arrays
5059     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5060     if (!stopped()) {
5061       // TODO 8251971
5062       if (!orig_t->is_null_free()) {
5063         // Not statically known to be null free, add a check
5064         generate_fair_guard(null_free_array_test(original), bailout);
5065       }
5066       orig_t = _gvn.type(original)->isa_aryptr();
5067       if (orig_t != nullptr && orig_t->is_flat()) {
5068         // Src is flat, check that dest is flat as well
5069         if (exclude_flat) {
5070           // Dest can't be flat, bail out
5071           bailout->add_req(control());
5072           set_control(top());
5073         } else {
5074           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5075         }
5076         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5077       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5078                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5079                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5080         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5081         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5082         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5083         if (orig_t != nullptr) {
5084           orig_t = orig_t->cast_to_not_flat();
5085           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5086         }
5087       }
5088       if (!can_validate) {
5089         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5090         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5091         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5092         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5093         generate_fair_guard(null_free_array_test(original), bailout);
5094       }
5095     }
5096 
5097     // Bail out if start is larger than the original length
5098     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5099     generate_negative_guard(orig_tail, bailout, &orig_tail);
5100 
5101     if (bailout->req() > 1) {
5102       PreserveJVMState pjvms(this);
5103       set_control(_gvn.transform(bailout));
5104       uncommon_trap(Deoptimization::Reason_intrinsic,
5105                     Deoptimization::Action_maybe_recompile);
5106     }
5107 
5108     if (!stopped()) {
5109       // How many elements will we copy from the original?
5110       // The answer is MinI(orig_tail, length).
5111       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5112 
5113       // Generate a direct call to the right arraycopy function(s).
5114       // We know the copy is disjoint but we might not know if the
5115       // oop stores need checking.
5116       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).

5122       // to the copyOf to be validated, including that the copy to the
5123       // new array won't trigger an ArrayStoreException. That subtype
5124       // check can be optimized if we know something on the type of
5125       // the input array from type speculation.
5126       if (_gvn.type(klass_node)->singleton()) {
5127         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5128         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5129 
5130         int test = C->static_subtype_check(superk, subk);
5131         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5132           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5133           if (t_original->speculative_type() != nullptr) {
5134             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5135           }
5136         }
5137       }
5138 
5139       bool validated = false;
5140       // Reason_class_check rather than Reason_intrinsic because we
5141       // want to intrinsify even if this traps.
5142       if (can_validate) {
5143         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5144 
5145         if (not_subtype_ctrl != top()) {
5146           PreserveJVMState pjvms(this);
5147           set_control(not_subtype_ctrl);
5148           uncommon_trap(Deoptimization::Reason_class_check,
5149                         Deoptimization::Action_make_not_entrant);
5150           assert(stopped(), "Should be stopped");
5151         }
5152         validated = true;
5153       }
5154 
5155       if (!stopped()) {
5156         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5157 
5158         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5159                                                 load_object_klass(original), klass_node);
5160         if (!is_copyOfRange) {
5161           ac->set_copyof(validated);
5162         } else {
5163           ac->set_copyofrange(validated);
5164         }
5165         Node* n = _gvn.transform(ac);
5166         if (n == ac) {
5167           ac->connect_outputs(this);
5168         } else {
5169           assert(validated, "shouldn't transform if all arguments not validated");
5170           set_all_memory(n);
5171         }
5172       }
5173     }
5174   } // original reexecute is set back here
5175 
5176   C->set_has_split_ifs(true); // Has chance for split-if optimization

5208 
5209 //-----------------------generate_method_call----------------------------
5210 // Use generate_method_call to make a slow-call to the real
5211 // method if the fast path fails.  An alternative would be to
5212 // use a stub like OptoRuntime::slow_arraycopy_Java.
5213 // This only works for expanding the current library call,
5214 // not another intrinsic.  (E.g., don't use this for making an
5215 // arraycopy call inside of the copyOf intrinsic.)
5216 CallJavaNode*
5217 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5218   // When compiling the intrinsic method itself, do not use this technique.
5219   guarantee(callee() != C->method(), "cannot make slow-call to self");
5220 
5221   ciMethod* method = callee();
5222   // ensure the JVMS we have will be correct for this call
5223   guarantee(method_id == method->intrinsic_id(), "must match");
5224 
5225   const TypeFunc* tf = TypeFunc::make(method);
5226   if (res_not_null) {
5227     assert(tf->return_type() == T_OBJECT, "");
5228     const TypeTuple* range = tf->range_cc();
5229     const Type** fields = TypeTuple::fields(range->cnt());
5230     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5231     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5232     tf = TypeFunc::make(tf->domain_cc(), new_range);
5233   }
5234   CallJavaNode* slow_call;
5235   if (is_static) {
5236     assert(!is_virtual, "");
5237     slow_call = new CallStaticJavaNode(C, tf,
5238                            SharedRuntime::get_resolve_static_call_stub(), method);
5239   } else if (is_virtual) {
5240     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5241     int vtable_index = Method::invalid_vtable_index;
5242     if (UseInlineCaches) {
5243       // Suppress the vtable call
5244     } else {
5245       // hashCode and clone are not a miranda methods,
5246       // so the vtable index is fixed.
5247       // No need to use the linkResolver to get it.
5248        vtable_index = method->vtable_index();
5249        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5250               "bad index %d", vtable_index);
5251     }
5252     slow_call = new CallDynamicJavaNode(tf,

5269   set_edges_for_java_call(slow_call);
5270   return slow_call;
5271 }
5272 
5273 
5274 /**
5275  * Build special case code for calls to hashCode on an object. This call may
5276  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5277  * slightly different code.
5278  */
5279 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5280   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5281   assert(!(is_virtual && is_static), "either virtual, special, or static");
5282 
5283   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5284 
5285   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5286   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5287   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5288   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5289   Node* obj = argument(0);
5290 
5291   // Don't intrinsify hashcode on inline types for now.
5292   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5293   if (gvn().type(obj)->is_inlinetypeptr()) {
5294     return false;
5295   }
5296 
5297   if (!is_static) {
5298     // Check for hashing null object
5299     obj = null_check_receiver();
5300     if (stopped())  return true;        // unconditionally null
5301     result_reg->init_req(_null_path, top());
5302     result_val->init_req(_null_path, top());
5303   } else {
5304     // Do a null check, and return zero if null.
5305     // System.identityHashCode(null) == 0

5306     Node* null_ctl = top();
5307     obj = null_check_oop(obj, &null_ctl);
5308     result_reg->init_req(_null_path, null_ctl);
5309     result_val->init_req(_null_path, _gvn.intcon(0));
5310   }
5311 
5312   // Unconditionally null?  Then return right away.
5313   if (stopped()) {
5314     set_control( result_reg->in(_null_path));
5315     if (!stopped())
5316       set_result(result_val->in(_null_path));
5317     return true;
5318   }
5319 
5320   // We only go to the fast case code if we pass a number of guards.  The
5321   // paths which do not pass are accumulated in the slow_region.
5322   RegionNode* slow_region = new RegionNode(1);
5323   record_for_igvn(slow_region);
5324 
5325   // If this is a virtual call, we generate a funny guard.  We pull out
5326   // the vtable entry corresponding to hashCode() from the target object.
5327   // If the target method which we are calling happens to be the native
5328   // Object hashCode() method, we pass the guard.  We do not need this
5329   // guard for non-virtual calls -- the caller is known to be the native
5330   // Object hashCode().
5331   if (is_virtual) {
5332     // After null check, get the object's klass.
5333     Node* obj_klass = load_object_klass(obj);
5334     generate_virtual_guard(obj_klass, slow_region);
5335   }
5336 
5337   // Get the header out of the object, use LoadMarkNode when available
5338   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5339   // The control of the load must be null. Otherwise, the load can move before
5340   // the null check after castPP removal.
5341   Node* no_ctrl = nullptr;
5342   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5343 
5344   if (!UseObjectMonitorTable) {
5345     // Test the header to see if it is safe to read w.r.t. locking.
5346     // We cannot use the inline type mask as this may check bits that are overriden
5347     // by an object monitor's pointer when inflating locking.
5348     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5349     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5350     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5351     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5352     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5353 
5354     generate_slow_guard(test_monitor, slow_region);
5355   }
5356 
5357   // Get the hash value and check to see that it has been properly assigned.
5358   // We depend on hash_mask being at most 32 bits and avoid the use of
5359   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5360   // vm: see markWord.hpp.
5361   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5362   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5363   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5364   // This hack lets the hash bits live anywhere in the mark object now, as long
5365   // as the shift drops the relevant bits into the low 32 bits.  Note that
5366   // Java spec says that HashCode is an int so there's no point in capturing
5367   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).

5395     // this->control() comes from set_results_for_java_call
5396     result_reg->init_req(_slow_path, control());
5397     result_val->init_req(_slow_path, slow_result);
5398     result_io  ->set_req(_slow_path, i_o());
5399     result_mem ->set_req(_slow_path, reset_memory());
5400   }
5401 
5402   // Return the combined state.
5403   set_i_o(        _gvn.transform(result_io)  );
5404   set_all_memory( _gvn.transform(result_mem));
5405 
5406   set_result(result_reg, result_val);
5407   return true;
5408 }
5409 
5410 //---------------------------inline_native_getClass----------------------------
5411 // public final native Class<?> java.lang.Object.getClass();
5412 //
5413 // Build special case code for calls to getClass on an object.
5414 bool LibraryCallKit::inline_native_getClass() {
5415   Node* obj = argument(0);
5416   if (obj->is_InlineType()) {
5417     const Type* t = _gvn.type(obj);
5418     if (t->maybe_null()) {
5419       null_check(obj);
5420     }
5421     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5422     return true;
5423   }
5424   obj = null_check_receiver();
5425   if (stopped())  return true;
5426   set_result(load_mirror_from_klass(load_object_klass(obj)));
5427   return true;
5428 }
5429 
5430 //-----------------inline_native_Reflection_getCallerClass---------------------
5431 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5432 //
5433 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5434 //
5435 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5436 // in that it must skip particular security frames and checks for
5437 // caller sensitive methods.
5438 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5439 #ifndef PRODUCT
5440   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5441     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5442   }
5443 #endif
5444 

5826 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5827 //
5828 // The general case has two steps, allocation and copying.
5829 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5830 //
5831 // Copying also has two cases, oop arrays and everything else.
5832 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5833 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5834 //
5835 // These steps fold up nicely if and when the cloned object's klass
5836 // can be sharply typed as an object array, a type array, or an instance.
5837 //
5838 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5839   PhiNode* result_val;
5840 
5841   // Set the reexecute bit for the interpreter to reexecute
5842   // the bytecode that invokes Object.clone if deoptimization happens.
5843   { PreserveReexecuteState preexecs(this);
5844     jvms()->set_should_reexecute(true);
5845 
5846     Node* obj = argument(0);
5847     obj = null_check_receiver();
5848     if (stopped())  return true;
5849 
5850     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5851     if (obj_type->is_inlinetypeptr()) {
5852       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5853       // no identity.
5854       set_result(obj);
5855       return true;
5856     }
5857 
5858     // If we are going to clone an instance, we need its exact type to
5859     // know the number and types of fields to convert the clone to
5860     // loads/stores. Maybe a speculative type can help us.
5861     if (!obj_type->klass_is_exact() &&
5862         obj_type->speculative_type() != nullptr &&
5863         obj_type->speculative_type()->is_instance_klass() &&
5864         !obj_type->speculative_type()->is_inlinetype()) {
5865       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5866       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5867           !spec_ik->has_injected_fields()) {
5868         if (!obj_type->isa_instptr() ||
5869             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5870           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5871         }
5872       }
5873     }
5874 
5875     // Conservatively insert a memory barrier on all memory slices.
5876     // Do not let writes into the original float below the clone.
5877     insert_mem_bar(Op_MemBarCPUOrder);
5878 
5879     // paths into result_reg:
5880     enum {
5881       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5882       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5883       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5884       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5885       PATH_LIMIT
5886     };
5887     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5888     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5889     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5890     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5891     record_for_igvn(result_reg);
5892 
5893     Node* obj_klass = load_object_klass(obj);
5894     // We only go to the fast case code if we pass a number of guards.
5895     // The paths which do not pass are accumulated in the slow_region.
5896     RegionNode* slow_region = new RegionNode(1);
5897     record_for_igvn(slow_region);
5898 
5899     Node* array_obj = obj;
5900     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5901     if (array_ctl != nullptr) {
5902       // It's an array.
5903       PreserveJVMState pjvms(this);
5904       set_control(array_ctl);



5905 
5906       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5907       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5908       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5909           obj_type->can_be_inline_array() &&
5910           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5911         // Flat inline type array may have object field that would require a
5912         // write barrier. Conservatively, go to slow path.
5913         generate_fair_guard(flat_array_test(obj_klass), slow_region);













5914       }







5915 
5916       if (!stopped()) {
5917         Node* obj_length = load_array_length(array_obj);
5918         Node* array_size = nullptr; // Size of the array without object alignment padding.
5919         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5920 
5921         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5922         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5923           // If it is an oop array, it requires very special treatment,
5924           // because gc barriers are required when accessing the array.
5925           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5926           if (is_obja != nullptr) {
5927             PreserveJVMState pjvms2(this);
5928             set_control(is_obja);
5929             // Generate a direct call to the right arraycopy function(s).
5930             // Clones are always tightly coupled.
5931             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5932             ac->set_clone_oop_array();
5933             Node* n = _gvn.transform(ac);
5934             assert(n == ac, "cannot disappear");
5935             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5936 
5937             result_reg->init_req(_objArray_path, control());
5938             result_val->init_req(_objArray_path, alloc_obj);
5939             result_i_o ->set_req(_objArray_path, i_o());
5940             result_mem ->set_req(_objArray_path, reset_memory());
5941           }
5942         }
5943         // Otherwise, there are no barriers to worry about.
5944         // (We can dispense with card marks if we know the allocation
5945         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5946         //  causes the non-eden paths to take compensating steps to
5947         //  simulate a fresh allocation, so that no further
5948         //  card marks are required in compiled code to initialize
5949         //  the object.)
5950 
5951         if (!stopped()) {
5952           copy_to_clone(obj, alloc_obj, array_size, true);
5953 
5954           // Present the results of the copy.
5955           result_reg->init_req(_array_path, control());
5956           result_val->init_req(_array_path, alloc_obj);
5957           result_i_o ->set_req(_array_path, i_o());
5958           result_mem ->set_req(_array_path, reset_memory());
5959         }
5960       }
5961     }
5962 




5963     if (!stopped()) {
5964       // It's an instance (we did array above).  Make the slow-path tests.
5965       // If this is a virtual call, we generate a funny guard.  We grab
5966       // the vtable entry corresponding to clone() from the target object.
5967       // If the target method which we are calling happens to be the
5968       // Object clone() method, we pass the guard.  We do not need this
5969       // guard for non-virtual calls; the caller is known to be the native
5970       // Object clone().
5971       if (is_virtual) {
5972         generate_virtual_guard(obj_klass, slow_region);
5973       }
5974 
5975       // The object must be easily cloneable and must not have a finalizer.
5976       // Both of these conditions may be checked in a single test.
5977       // We could optimize the test further, but we don't care.
5978       generate_misc_flags_guard(obj_klass,
5979                                 // Test both conditions:
5980                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5981                                 // Must be cloneable but not finalizer:
5982                                 KlassFlags::_misc_is_cloneable_fast,

6074         set_jvms(sfpt->jvms());
6075         _reexecute_sp = jvms()->sp();
6076 
6077         return saved_jvms;
6078       }
6079     }
6080   }
6081   return nullptr;
6082 }
6083 
6084 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6085 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6086 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6087   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6088   uint size = alloc->req();
6089   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6090   old_jvms->set_map(sfpt);
6091   for (uint i = 0; i < size; i++) {
6092     sfpt->init_req(i, alloc->in(i));
6093   }
6094   int adjustment = 1;
6095   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6096   if (ary_klass_ptr->is_null_free()) {
6097     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6098     // also requires the componentType and initVal on stack for re-execution.
6099     // Re-create and push the componentType.
6100     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6101     ciInstance* instance = klass->component_mirror_instance();
6102     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6103     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6104     adjustment++;
6105   }
6106   // re-push array length for deoptimization
6107   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6108   if (ary_klass_ptr->is_null_free()) {
6109     // Re-create and push the initVal.
6110     Node* init_val = alloc->in(AllocateNode::InitValue);
6111     if (init_val == nullptr) {
6112       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6113     } else if (UseCompressedOops) {
6114       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6115     }
6116     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6117     adjustment++;
6118   }
6119   old_jvms->set_sp(old_jvms->sp() + adjustment);
6120   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6121   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6122   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6123   old_jvms->set_should_reexecute(true);
6124 
6125   sfpt->set_i_o(map()->i_o());
6126   sfpt->set_memory(map()->memory());
6127   sfpt->set_control(map()->control());
6128   return sfpt;
6129 }
6130 
6131 // In case of a deoptimization, we restart execution at the
6132 // allocation, allocating a new array. We would leave an uninitialized
6133 // array in the heap that GCs wouldn't expect. Move the allocation
6134 // after the traps so we don't allocate the array if we
6135 // deoptimize. This is possible because tightly_coupled_allocation()
6136 // guarantees there's no observer of the allocated array at this point
6137 // and the control flow is simple enough.
6138 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6139                                                     int saved_reexecute_sp, uint new_idx) {
6140   if (saved_jvms_before_guards != nullptr && !stopped()) {
6141     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6142 
6143     assert(alloc != nullptr, "only with a tightly coupled allocation");
6144     // restore JVM state to the state at the arraycopy
6145     saved_jvms_before_guards->map()->set_control(map()->control());
6146     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6147     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6148     // If we've improved the types of some nodes (null check) while
6149     // emitting the guards, propagate them to the current state
6150     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6151     set_jvms(saved_jvms_before_guards);
6152     _reexecute_sp = saved_reexecute_sp;
6153 
6154     // Remove the allocation from above the guards
6155     CallProjections* callprojs = alloc->extract_projections(true);

6156     InitializeNode* init = alloc->initialization();
6157     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6158     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6159     init->replace_mem_projs_by(alloc_mem, C);
6160 
6161     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6162     // the allocation (i.e. is only valid if the allocation succeeds):
6163     // 1) replace CastIINode with AllocateArrayNode's length here
6164     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6165     //
6166     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6167     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6168     Node* init_control = init->proj_out(TypeFunc::Control);
6169     Node* alloc_length = alloc->Ideal_length();
6170 #ifdef ASSERT
6171     Node* prev_cast = nullptr;
6172 #endif
6173     for (uint i = 0; i < init_control->outcnt(); i++) {
6174       Node* init_out = init_control->raw_out(i);
6175       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6176 #ifdef ASSERT
6177         if (prev_cast == nullptr) {
6178           prev_cast = init_out;

6180           if (prev_cast->cmp(*init_out) == false) {
6181             prev_cast->dump();
6182             init_out->dump();
6183             assert(false, "not equal CastIINode");
6184           }
6185         }
6186 #endif
6187         C->gvn_replace_by(init_out, alloc_length);
6188       }
6189     }
6190     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6191 
6192     // move the allocation here (after the guards)
6193     _gvn.hash_delete(alloc);
6194     alloc->set_req(TypeFunc::Control, control());
6195     alloc->set_req(TypeFunc::I_O, i_o());
6196     Node *mem = reset_memory();
6197     set_all_memory(mem);
6198     alloc->set_req(TypeFunc::Memory, mem);
6199     set_control(init->proj_out_or_null(TypeFunc::Control));
6200     set_i_o(callprojs->fallthrough_ioproj);
6201 
6202     // Update memory as done in GraphKit::set_output_for_allocation()
6203     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6204     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6205     if (ary_type->isa_aryptr() && length_type != nullptr) {
6206       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6207     }
6208     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6209     int            elemidx  = C->get_alias_index(telemref);
6210     // Need to properly move every memory projection for the Initialize
6211 #ifdef ASSERT
6212     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6213     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6214 #endif
6215     auto move_proj = [&](ProjNode* proj) {
6216       int alias_idx = C->get_alias_index(proj->adr_type());
6217       assert(alias_idx == Compile::AliasIdxRaw ||
6218              alias_idx == elemidx ||
6219              alias_idx == mark_idx ||
6220              alias_idx == klass_idx, "should be raw memory or array element type");

6530         top_src  = src_type->isa_aryptr();
6531         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6532         src_spec = true;
6533       }
6534       if (!has_dest) {
6535         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6536         dest_type  = _gvn.type(dest);
6537         top_dest  = dest_type->isa_aryptr();
6538         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6539         dest_spec = true;
6540       }
6541     }
6542   }
6543 
6544   if (has_src && has_dest && can_emit_guards) {
6545     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6546     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6547     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6548     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6549 
6550     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6551       // If both arrays are object arrays then having the exact types
6552       // for both will remove the need for a subtype check at runtime
6553       // before the call and may make it possible to pick a faster copy
6554       // routine (without a subtype check on every element)
6555       // Do we have the exact type of src?
6556       bool could_have_src = src_spec;
6557       // Do we have the exact type of dest?
6558       bool could_have_dest = dest_spec;
6559       ciKlass* src_k = nullptr;
6560       ciKlass* dest_k = nullptr;
6561       if (!src_spec) {
6562         src_k = src_type->speculative_type_not_null();
6563         if (src_k != nullptr && src_k->is_array_klass()) {
6564           could_have_src = true;
6565         }
6566       }
6567       if (!dest_spec) {
6568         dest_k = dest_type->speculative_type_not_null();
6569         if (dest_k != nullptr && dest_k->is_array_klass()) {
6570           could_have_dest = true;
6571         }
6572       }
6573       if (could_have_src && could_have_dest) {
6574         // If we can have both exact types, emit the missing guards
6575         if (could_have_src && !src_spec) {
6576           src = maybe_cast_profiled_obj(src, src_k, true);
6577           src_type = _gvn.type(src);
6578           top_src = src_type->isa_aryptr();
6579         }
6580         if (could_have_dest && !dest_spec) {
6581           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6582           dest_type = _gvn.type(dest);
6583           top_dest = dest_type->isa_aryptr();
6584         }
6585       }
6586     }
6587   }
6588 
6589   ciMethod* trap_method = method();
6590   int trap_bci = bci();
6591   if (saved_jvms_before_guards != nullptr) {
6592     trap_method = alloc->jvms()->method();
6593     trap_bci = alloc->jvms()->bci();
6594   }
6595 
6596   bool negative_length_guard_generated = false;
6597 
6598   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6599       can_emit_guards && !src->is_top() && !dest->is_top()) {

6600     // validate arguments: enables transformation the ArrayCopyNode
6601     validated = true;
6602 
6603     RegionNode* slow_region = new RegionNode(1);
6604     record_for_igvn(slow_region);
6605 
6606     // (1) src and dest are arrays.
6607     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6608     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6609 
6610     // (2) src and dest arrays must have elements of the same BasicType
6611     // done at macro expansion or at Ideal transformation time
6612 
6613     // (4) src_offset must not be negative.
6614     generate_negative_guard(src_offset, slow_region);
6615 
6616     // (5) dest_offset must not be negative.
6617     generate_negative_guard(dest_offset, slow_region);
6618 
6619     // (7) src_offset + length must not exceed length of src.
6620     generate_limit_guard(src_offset, length,
6621                          load_array_length(src),
6622                          slow_region);
6623 
6624     // (8) dest_offset + length must not exceed length of dest.
6625     generate_limit_guard(dest_offset, length,
6626                          load_array_length(dest),
6627                          slow_region);
6628 
6629     // (6) length must not be negative.
6630     // This is also checked in generate_arraycopy() during macro expansion, but
6631     // we also have to check it here for the case where the ArrayCopyNode will
6632     // be eliminated by Escape Analysis.
6633     if (EliminateAllocations) {
6634       generate_negative_guard(length, slow_region);
6635       negative_length_guard_generated = true;
6636     }
6637 
6638     // (9) each element of an oop array must be assignable
6639     Node* dest_klass = load_object_klass(dest);
6640     Node* refined_dest_klass = dest_klass;
6641     if (src != dest) {
6642       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6643       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6644       slow_region->add_req(not_subtype_ctrl);







6645     }
6646 
6647     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6648     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6649     Node* src_klass = load_object_klass(src);
6650     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6651     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6652                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6653                                                    MemNode::unordered));
6654     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6655     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6656                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6657                                                     MemNode::unordered));
6658 
6659     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6660     jint props_value = (jint)props_null_restricted.value();
6661 
6662     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6663     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6664     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6665 
6666     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6667     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6668     generate_fair_guard(tst, slow_region);
6669 
6670     // TODO 8350865 This is too strong
6671     generate_fair_guard(flat_array_test(src), slow_region);
6672     generate_fair_guard(flat_array_test(dest), slow_region);
6673 
6674     {
6675       PreserveJVMState pjvms(this);
6676       set_control(_gvn.transform(slow_region));
6677       uncommon_trap(Deoptimization::Reason_intrinsic,
6678                     Deoptimization::Action_make_not_entrant);
6679       assert(stopped(), "Should be stopped");
6680     }
6681 
6682     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6683     if (dest_klass_t == nullptr) {
6684       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6685       // are in a dead path.
6686       uncommon_trap(Deoptimization::Reason_intrinsic,
6687                     Deoptimization::Action_make_not_entrant);
6688       return true;
6689     }
6690 
6691     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6692     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6693     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6694   }
6695 
6696   if (stopped()) {
6697     return true;
6698   }
6699 
6700   Node* dest_klass = load_object_klass(dest);
6701   dest_klass = load_non_refined_array_klass(dest_klass);
6702 
6703   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6704                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6705                                           // so the compiler has a chance to eliminate them: during macro expansion,
6706                                           // we have to set their control (CastPP nodes are eliminated).
6707                                           load_object_klass(src), dest_klass,
6708                                           load_array_length(src), load_array_length(dest));
6709 
6710   ac->set_arraycopy(validated);
6711 
6712   Node* n = _gvn.transform(ac);
6713   if (n == ac) {
6714     ac->connect_outputs(this);
6715   } else {
6716     assert(validated, "shouldn't transform if all arguments not validated");
6717     set_all_memory(n);
6718   }
6719   clear_upper_avx();
6720 
6721 
6722   return true;
6723 }
6724 
6725 
6726 // Helper function which determines if an arraycopy immediately follows
6727 // an allocation, with no intervening tests or other escapes for the object.
< prev index next >