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);
500 #endif
501 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
502 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
503 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
504 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
505 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
506 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
507 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
508 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
509 case vmIntrinsics::_getLength: return inline_native_getLength();
510 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
511 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
512 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
513 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
514 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
515 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
516 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
517
518 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
519 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
520
521 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
522
523 case vmIntrinsics::_isInstance:
524 case vmIntrinsics::_isHidden:
525 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
526
527 case vmIntrinsics::_floatToRawIntBits:
528 case vmIntrinsics::_floatToIntBits:
529 case vmIntrinsics::_intBitsToFloat:
530 case vmIntrinsics::_doubleToRawLongBits:
531 case vmIntrinsics::_doubleToLongBits:
532 case vmIntrinsics::_longBitsToDouble:
533 case vmIntrinsics::_floatToFloat16:
534 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
535 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
536 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
537 case vmIntrinsics::_floatIsFinite:
538 case vmIntrinsics::_floatIsInfinite:
539 case vmIntrinsics::_doubleIsFinite:
2265 case vmIntrinsics::_remainderUnsigned_l: {
2266 zero_check_long(argument(2));
2267 // Compile-time detect of null-exception
2268 if (stopped()) {
2269 return true; // keep the graph constructed so far
2270 }
2271 n = new UModLNode(control(), argument(0), argument(2));
2272 break;
2273 }
2274 default: fatal_unexpected_iid(id); break;
2275 }
2276 set_result(_gvn.transform(n));
2277 return true;
2278 }
2279
2280 //----------------------------inline_unsafe_access----------------------------
2281
2282 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2283 // Attempt to infer a sharper value type from the offset and base type.
2284 ciKlass* sharpened_klass = nullptr;
2285
2286 // See if it is an instance field, with an object type.
2287 if (alias_type->field() != nullptr) {
2288 if (alias_type->field()->type()->is_klass()) {
2289 sharpened_klass = alias_type->field()->type()->as_klass();
2290 }
2291 }
2292
2293 const TypeOopPtr* result = nullptr;
2294 // See if it is a narrow oop array.
2295 if (adr_type->isa_aryptr()) {
2296 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2297 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2298 if (elem_type != nullptr && elem_type->is_loaded()) {
2299 // Sharpen the value type.
2300 result = elem_type;
2301 }
2302 }
2303 }
2304
2305 // The sharpened class might be unloaded if there is no class loader
2306 // contraint in place.
2307 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2308 // Sharpen the value type.
2309 result = TypeOopPtr::make_from_klass(sharpened_klass);
2310 }
2311 if (result != nullptr) {
2312 #ifndef PRODUCT
2313 if (C->print_intrinsics() || C->print_inlining()) {
2314 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2315 tty->print(" sharpened value: "); result->dump(); tty->cr();
2316 }
2317 #endif
2318 }
2319 return result;
2320 }
2321
2322 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2323 switch (kind) {
2324 case Relaxed:
2325 return MO_UNORDERED;
2326 case Opaque:
2327 return MO_RELAXED;
2328 case Acquire:
2329 return MO_ACQUIRE;
2377 #endif // ASSERT
2378 }
2379 #endif //PRODUCT
2380
2381 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2382
2383 Node* receiver = argument(0); // type: oop
2384
2385 // Build address expression.
2386 Node* heap_base_oop = top();
2387
2388 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2389 Node* base = argument(1); // type: oop
2390 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2391 Node* offset = argument(2); // type: long
2392 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2393 // to be plain byte offsets, which are also the same as those accepted
2394 // by oopDesc::field_addr.
2395 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2396 "fieldOffset must be byte-scaled");
2397 // 32-bit machines ignore the high half!
2398 offset = ConvL2X(offset);
2399
2400 // Save state and restore on bailout
2401 SavedState old_state(this);
2402
2403 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2404 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2405
2406 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2407 if (type != T_OBJECT) {
2408 decorators |= IN_NATIVE; // off-heap primitive access
2409 } else {
2410 return false; // off-heap oop accesses are not supported
2411 }
2412 } else {
2413 heap_base_oop = base; // on-heap or mixed access
2414 }
2415
2416 // Can base be null? Otherwise, always on-heap access.
2420 decorators |= IN_HEAP;
2421 }
2422
2423 Node* val = is_store ? argument(4) : nullptr;
2424
2425 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2426 if (adr_type == TypePtr::NULL_PTR) {
2427 return false; // off-heap access with zero address
2428 }
2429
2430 // Try to categorize the address.
2431 Compile::AliasType* alias_type = C->alias_type(adr_type);
2432 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2433
2434 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2435 alias_type->adr_type() == TypeAryPtr::RANGE) {
2436 return false; // not supported
2437 }
2438
2439 bool mismatched = false;
2440 BasicType bt = alias_type->basic_type();
2441 if (bt != T_ILLEGAL) {
2442 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2443 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2444 // Alias type doesn't differentiate between byte[] and boolean[]).
2445 // Use address type to get the element type.
2446 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2447 }
2448 if (is_reference_type(bt, true)) {
2449 // accessing an array field with getReference is not a mismatch
2450 bt = T_OBJECT;
2451 }
2452 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2453 // Don't intrinsify mismatched object accesses
2454 return false;
2455 }
2456 mismatched = (bt != type);
2457 } else if (alias_type->adr_type()->isa_oopptr()) {
2458 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2459 }
2460
2461 old_state.discard();
2462 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2463
2464 if (mismatched) {
2465 decorators |= C2_MISMATCHED;
2466 }
2467
2468 // First guess at the value type.
2469 const Type *value_type = Type::get_const_basic_type(type);
2470
2471 // Figure out the memory ordering.
2472 decorators |= mo_decorator_for_access_kind(kind);
2473
2474 if (!is_store && type == T_OBJECT) {
2475 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2476 if (tjp != nullptr) {
2477 value_type = tjp;
2478 }
2479 }
2480
2481 receiver = null_check(receiver);
2482 if (stopped()) {
2483 return true;
2484 }
2485 // Heap pointers get a null-check from the interpreter,
2486 // as a courtesy. However, this is not guaranteed by Unsafe,
2487 // and it is not possible to fully distinguish unintended nulls
2488 // from intended ones in this API.
2489
2490 if (!is_store) {
2491 Node* p = nullptr;
2492 // Try to constant fold a load from a constant field
2493 ciField* field = alias_type->field();
2494 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2495 // final or stable field
2496 p = make_constant_from_field(field, heap_base_oop);
2497 }
2498
2499 if (p == nullptr) { // Could not constant fold the load
2500 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2501 // Normalize the value returned by getBoolean in the following cases
2502 if (type == T_BOOLEAN &&
2503 (mismatched ||
2504 heap_base_oop == top() || // - heap_base_oop is null or
2505 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2506 // and the unsafe access is made to large offset
2507 // (i.e., larger than the maximum offset necessary for any
2508 // field access)
2509 ) {
2510 IdealKit ideal = IdealKit(this);
2511 #define __ ideal.
2512 IdealVariable normalized_result(ideal);
2513 __ declarations_done();
2514 __ set(normalized_result, p);
2515 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2516 __ set(normalized_result, ideal.ConI(1));
2517 ideal.end_if();
2518 final_sync(ideal);
2519 p = __ value(normalized_result);
2520 #undef __
2524 p = gvn().transform(new CastP2XNode(nullptr, p));
2525 p = ConvX2UL(p);
2526 }
2527 // The load node has the control of the preceding MemBarCPUOrder. All
2528 // following nodes will have the control of the MemBarCPUOrder inserted at
2529 // the end of this method. So, pushing the load onto the stack at a later
2530 // point is fine.
2531 set_result(p);
2532 } else {
2533 if (bt == T_ADDRESS) {
2534 // Repackage the long as a pointer.
2535 val = ConvL2X(val);
2536 val = gvn().transform(new CastX2PNode(val));
2537 }
2538 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2539 }
2540
2541 return true;
2542 }
2543
2544 //----------------------------inline_unsafe_load_store----------------------------
2545 // This method serves a couple of different customers (depending on LoadStoreKind):
2546 //
2547 // LS_cmp_swap:
2548 //
2549 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2550 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2551 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2552 //
2553 // LS_cmp_swap_weak:
2554 //
2555 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2556 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2557 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2558 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2559 //
2560 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2561 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2562 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2563 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2726 }
2727 case LS_cmp_swap:
2728 case LS_cmp_swap_weak:
2729 case LS_get_add:
2730 break;
2731 default:
2732 ShouldNotReachHere();
2733 }
2734
2735 // Null check receiver.
2736 receiver = null_check(receiver);
2737 if (stopped()) {
2738 return true;
2739 }
2740
2741 int alias_idx = C->get_alias_index(adr_type);
2742
2743 if (is_reference_type(type)) {
2744 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2745
2746 // Transformation of a value which could be null pointer (CastPP #null)
2747 // could be delayed during Parse (for example, in adjust_map_after_if()).
2748 // Execute transformation here to avoid barrier generation in such case.
2749 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2750 newval = _gvn.makecon(TypePtr::NULL_PTR);
2751
2752 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2753 // Refine the value to a null constant, when it is known to be null
2754 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2755 }
2756 }
2757
2758 Node* result = nullptr;
2759 switch (kind) {
2760 case LS_cmp_exchange: {
2761 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2762 oldval, newval, value_type, type, decorators);
2763 break;
2764 }
2765 case LS_cmp_swap_weak:
2794 insert_mem_bar(Op_MemBarCPUOrder);
2795 switch(id) {
2796 case vmIntrinsics::_loadFence:
2797 insert_mem_bar(Op_LoadFence);
2798 return true;
2799 case vmIntrinsics::_storeFence:
2800 insert_mem_bar(Op_StoreFence);
2801 return true;
2802 case vmIntrinsics::_storeStoreFence:
2803 insert_mem_bar(Op_StoreStoreFence);
2804 return true;
2805 case vmIntrinsics::_fullFence:
2806 insert_mem_bar(Op_MemBarFull);
2807 return true;
2808 default:
2809 fatal_unexpected_iid(id);
2810 return false;
2811 }
2812 }
2813
2814 bool LibraryCallKit::inline_onspinwait() {
2815 insert_mem_bar(Op_OnSpinWait);
2816 return true;
2817 }
2818
2819 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2820 if (!kls->is_Con()) {
2821 return true;
2822 }
2823 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2824 if (klsptr == nullptr) {
2825 return true;
2826 }
2827 ciInstanceKlass* ik = klsptr->instance_klass();
2828 // don't need a guard for a klass that is already initialized
2829 return !ik->is_initialized();
2830 }
2831
2832 //----------------------------inline_unsafe_writeback0-------------------------
2833 // public native void Unsafe.writeback0(long address)
2912 Deoptimization::Action_make_not_entrant);
2913 }
2914 if (stopped()) {
2915 return true;
2916 }
2917 #endif //INCLUDE_JVMTI
2918
2919 Node* test = nullptr;
2920 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2921 // Note: The argument might still be an illegal value like
2922 // Serializable.class or Object[].class. The runtime will handle it.
2923 // But we must make an explicit check for initialization.
2924 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
2925 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2926 // can generate code to load it as unsigned byte.
2927 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2928 Node* bits = intcon(InstanceKlass::fully_initialized);
2929 test = _gvn.transform(new SubINode(inst, bits));
2930 // The 'test' is non-zero if we need to take a slow path.
2931 }
2932
2933 Node* obj = new_instance(kls, test);
2934 set_result(obj);
2935 return true;
2936 }
2937
2938 //------------------------inline_native_time_funcs--------------
2939 // inline code for System.currentTimeMillis() and System.nanoTime()
2940 // these have the same type and signature
2941 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2942 const TypeFunc* tf = OptoRuntime::void_long_Type();
2943 const TypePtr* no_memory_effects = nullptr;
2944 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2945 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2946 #ifdef ASSERT
2947 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2948 assert(value_top == top(), "second value must be top");
2949 #endif
2950 set_result(value);
2951 return true;
2952 }
3843 Node* arr = argument(1);
3844 Node* thread = _gvn.transform(new ThreadLocalNode());
3845 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
3846 Node* thread_obj_handle
3847 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3848 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3849 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3850
3851 // Change the _monitor_owner_id of the JavaThread
3852 Node* tid = load_field_from_object(arr, "tid", "J");
3853 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3854 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3855
3856 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3857 return true;
3858 }
3859
3860 const Type* LibraryCallKit::scopedValueCache_type() {
3861 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3862 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3863 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3864
3865 // Because we create the scopedValue cache lazily we have to make the
3866 // type of the result BotPTR.
3867 bool xk = etype->klass_is_exact();
3868 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3869 return objects_type;
3870 }
3871
3872 Node* LibraryCallKit::scopedValueCache_helper() {
3873 Node* thread = _gvn.transform(new ThreadLocalNode());
3874 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
3875 // We cannot use immutable_memory() because we might flip onto a
3876 // different carrier thread, at which point we'll need to use that
3877 // carrier thread's cache.
3878 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3879 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3880 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3881 }
3882
3883 //------------------------inline_native_scopedValueCache------------------
3884 bool LibraryCallKit::inline_native_scopedValueCache() {
3885 Node* cache_obj_handle = scopedValueCache_helper();
3886 const Type* objects_type = scopedValueCache_type();
3887 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3888
4024 }
4025 return kls;
4026 }
4027
4028 //--------------------(inline_native_Class_query helpers)---------------------
4029 // Use this for JVM_ACC_INTERFACE.
4030 // Fall through if (mods & mask) == bits, take the guard otherwise.
4031 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4032 ByteSize offset, const Type* type, BasicType bt) {
4033 // Branch around if the given klass has the given modifier bit set.
4034 // Like generate_guard, adds a new path onto the region.
4035 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4036 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4037 Node* mask = intcon(modifier_mask);
4038 Node* bits = intcon(modifier_bits);
4039 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4040 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4041 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4042 return generate_fair_guard(bol, region);
4043 }
4044 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4045 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4046 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4047 }
4048
4049 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4050 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4051 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4052 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4053 }
4054
4055 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4056 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4057 }
4058
4059 //-------------------------inline_native_Class_query-------------------
4060 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4061 const Type* return_type = TypeInt::BOOL;
4062 Node* prim_return_value = top(); // what happens if it's a primitive class?
4063 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4149
4150
4151 case vmIntrinsics::_getSuperclass:
4152 // The rules here are somewhat unfortunate, but we can still do better
4153 // with random logic than with a JNI call.
4154 // Interfaces store null or Object as _super, but must report null.
4155 // Arrays store an intermediate super as _super, but must report Object.
4156 // Other types can report the actual _super.
4157 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4158 if (generate_array_guard(kls, region) != nullptr) {
4159 // A guard was added. If the guard is taken, it was an array.
4160 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4161 }
4162 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4163 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4164 if (generate_interface_guard(kls, region) != nullptr) {
4165 // A guard was added. If the guard is taken, it was an interface.
4166 phi->add_req(null());
4167 }
4168 // If we fall through, it's a plain class. Get its _super.
4169 p = off_heap_plus_addr(kls, in_bytes(Klass::super_offset()));
4170 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4171 null_ctl = top();
4172 kls = null_check_oop(kls, &null_ctl);
4173 if (null_ctl != top()) {
4174 // If the guard is taken, Object.superClass is null (both klass and mirror).
4175 region->add_req(null_ctl);
4176 phi ->add_req(null());
4177 }
4178 if (!stopped()) {
4179 query_value = load_mirror_from_klass(kls);
4180 }
4181 break;
4182
4183 default:
4184 fatal_unexpected_iid(id);
4185 break;
4186 }
4187
4188 // Fall-through is the normal case of a query to a real class.
4189 phi->init_req(1, query_value);
4190 region->init_req(1, control());
4191
4192 C->set_has_split_ifs(true); // Has chance for split-if optimization
4193 set_result(region, phi);
4194 return true;
4195 }
4196
4197 //-------------------------inline_Class_cast-------------------
4198 bool LibraryCallKit::inline_Class_cast() {
4199 Node* mirror = argument(0); // Class
4200 Node* obj = argument(1);
4201 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4202 if (mirror_con == nullptr) {
4203 return false; // dead path (mirror->is_top()).
4204 }
4205 if (obj == nullptr || obj->is_top()) {
4206 return false; // dead path
4207 }
4208 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4209
4210 // First, see if Class.cast() can be folded statically.
4211 // java_mirror_type() returns non-null for compile-time Class constants.
4212 ciType* tm = mirror_con->java_mirror_type();
4213 if (tm != nullptr && tm->is_klass() &&
4214 tp != nullptr) {
4215 if (!tp->is_loaded()) {
4216 // Don't use intrinsic when class is not loaded.
4217 return false;
4218 } else {
4219 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4220 if (static_res == Compile::SSC_always_true) {
4221 // isInstance() is true - fold the code.
4222 set_result(obj);
4223 return true;
4224 } else if (static_res == Compile::SSC_always_false) {
4225 // Don't use intrinsic, have to throw ClassCastException.
4226 // If the reference is null, the non-intrinsic bytecode will
4227 // be optimized appropriately.
4228 return false;
4229 }
4230 }
4231 }
4232
4233 // Bailout intrinsic and do normal inlining if exception path is frequent.
4234 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4235 return false;
4236 }
4237
4238 // Generate dynamic checks.
4239 // Class.cast() is java implementation of _checkcast bytecode.
4240 // Do checkcast (Parse::do_checkcast()) optimizations here.
4241
4242 mirror = null_check(mirror);
4243 // If mirror is dead, only null-path is taken.
4244 if (stopped()) {
4245 return true;
4246 }
4247
4248 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4249 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4250 RegionNode* region = new RegionNode(PATH_LIMIT);
4251 record_for_igvn(region);
4252
4253 // Now load the mirror's klass metaobject, and null-check it.
4254 // If kls is null, we have a primitive mirror and
4255 // nothing is an instance of a primitive type.
4256 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4257
4258 Node* res = top();
4259 if (!stopped()) {
4260 Node* bad_type_ctrl = top();
4261 // Do checkcast optimizations.
4262 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4263 region->init_req(_bad_type_path, bad_type_ctrl);
4264 }
4265 if (region->in(_prim_path) != top() ||
4266 region->in(_bad_type_path) != top()) {
4267 // Let Interpreter throw ClassCastException.
4268 PreserveJVMState pjvms(this);
4269 set_control(_gvn.transform(region));
4270 uncommon_trap(Deoptimization::Reason_intrinsic,
4271 Deoptimization::Action_maybe_recompile);
4272 }
4273 if (!stopped()) {
4274 set_result(res);
4275 }
4276 return true;
4277 }
4278
4279
4280 //--------------------------inline_native_subtype_check------------------------
4281 // This intrinsic takes the JNI calls out of the heart of
4282 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4283 bool LibraryCallKit::inline_native_subtype_check() {
4284 // Pull both arguments off the stack.
4285 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4286 args[0] = argument(0);
4287 args[1] = argument(1);
4288 Node* klasses[2]; // corresponding Klasses: superk, subk
4289 klasses[0] = klasses[1] = top();
4290
4291 enum {
4292 // A full decision tree on {superc is prim, subc is prim}:
4293 _prim_0_path = 1, // {P,N} => false
4294 // {P,P} & superc!=subc => false
4295 _prim_same_path, // {P,P} & superc==subc => true
4296 _prim_1_path, // {N,P} => false
4297 _ref_subtype_path, // {N,N} & subtype check wins => true
4298 _both_ref_path, // {N,N} & subtype check loses => false
4299 PATH_LIMIT
4300 };
4301
4302 RegionNode* region = new RegionNode(PATH_LIMIT);
4303 Node* phi = new PhiNode(region, TypeInt::BOOL);
4304 record_for_igvn(region);
4305
4306 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4307 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4308 int class_klass_offset = java_lang_Class::klass_offset();
4309
4310 // First null-check both mirrors and load each mirror's klass metaobject.
4311 int which_arg;
4312 for (which_arg = 0; which_arg <= 1; which_arg++) {
4313 Node* arg = args[which_arg];
4314 arg = null_check(arg);
4315 if (stopped()) break;
4316 args[which_arg] = arg;
4317
4318 Node* p = basic_plus_adr(arg, class_klass_offset);
4319 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4320 klasses[which_arg] = _gvn.transform(kls);
4321 }
4322
4323 // Having loaded both klasses, test each for null.
4324 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4325 for (which_arg = 0; which_arg <= 1; which_arg++) {
4326 Node* kls = klasses[which_arg];
4327 Node* null_ctl = top();
4328 kls = null_check_oop(kls, &null_ctl, never_see_null);
4329 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4330 region->init_req(prim_path, null_ctl);
4331 if (stopped()) break;
4332 klasses[which_arg] = kls;
4333 }
4334
4335 if (!stopped()) {
4336 // now we have two reference types, in klasses[0..1]
4337 Node* subk = klasses[1]; // the argument to isAssignableFrom
4338 Node* superk = klasses[0]; // the receiver
4339 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4340 // now we have a successful reference subtype check
4341 region->set_req(_ref_subtype_path, control());
4342 }
4343
4344 // If both operands are primitive (both klasses null), then
4345 // we must return true when they are identical primitives.
4346 // It is convenient to test this after the first null klass check.
4347 set_control(region->in(_prim_0_path)); // go back to first null check
4348 if (!stopped()) {
4349 // Since superc is primitive, make a guard for the superc==subc case.
4350 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4351 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4352 generate_guard(bol_eq, region, PROB_FAIR);
4353 if (region->req() == PATH_LIMIT+1) {
4354 // A guard was added. If the added guard is taken, superc==subc.
4355 region->swap_edges(PATH_LIMIT, _prim_same_path);
4356 region->del_req(PATH_LIMIT);
4357 }
4358 region->set_req(_prim_0_path, control()); // Not equal after all.
4359 }
4360
4361 // these are the only paths that produce 'true':
4362 phi->set_req(_prim_same_path, intcon(1));
4363 phi->set_req(_ref_subtype_path, intcon(1));
4364
4365 // pull together the cases:
4366 assert(region->req() == PATH_LIMIT, "sane region");
4367 for (uint i = 1; i < region->req(); i++) {
4368 Node* ctl = region->in(i);
4369 if (ctl == nullptr || ctl == top()) {
4370 region->set_req(i, top());
4371 phi ->set_req(i, top());
4372 } else if (phi->in(i) == nullptr) {
4373 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4374 }
4375 }
4376
4377 set_control(_gvn.transform(region));
4378 set_result(_gvn.transform(phi));
4379 return true;
4380 }
4381
4382 //---------------------generate_array_guard_common------------------------
4383 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4384 bool obj_array, bool not_array, Node** obj) {
4385
4386 if (stopped()) {
4387 return nullptr;
4388 }
4389
4390 // If obj_array/non_array==false/false:
4391 // Branch around if the given klass is in fact an array (either obj or prim).
4392 // If obj_array/non_array==false/true:
4393 // Branch around if the given klass is not an array klass of any kind.
4394 // If obj_array/non_array==true/true:
4395 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4396 // If obj_array/non_array==true/false:
4397 // Branch around if the kls is an oop array (Object[] or subtype)
4398 //
4399 // Like generate_guard, adds a new path onto the region.
4400 jint layout_con = 0;
4401 Node* layout_val = get_layout_helper(kls, layout_con);
4402 if (layout_val == nullptr) {
4403 bool query = (obj_array
4404 ? Klass::layout_helper_is_objArray(layout_con)
4405 : Klass::layout_helper_is_array(layout_con));
4406 if (query == not_array) {
4407 return nullptr; // never a branch
4408 } else { // always a branch
4409 Node* always_branch = control();
4410 if (region != nullptr)
4411 region->add_req(always_branch);
4412 set_control(top());
4413 return always_branch;
4414 }
4415 }
4416 // Now test the correct condition.
4417 jint nval = (obj_array
4418 ? (jint)(Klass::_lh_array_tag_type_value
4419 << Klass::_lh_array_tag_shift)
4420 : Klass::_lh_neutral_value);
4421 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4422 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4423 // invert the test if we are looking for a non-array
4424 if (not_array) btest = BoolTest(btest).negate();
4425 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4426 Node* ctrl = generate_fair_guard(bol, region);
4427 Node* is_array_ctrl = not_array ? control() : ctrl;
4428 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4429 // Keep track of the fact that 'obj' is an array to prevent
4430 // array specific accesses from floating above the guard.
4431 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4432 }
4433 return ctrl;
4434 }
4435
4436
4437 //-----------------------inline_native_newArray--------------------------
4438 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4439 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4440 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4441 Node* mirror;
4442 Node* count_val;
4443 if (uninitialized) {
4444 null_check_receiver();
4445 mirror = argument(1);
4446 count_val = argument(2);
4447 } else {
4448 mirror = argument(0);
4449 count_val = argument(1);
4450 }
4451
4452 mirror = null_check(mirror);
4453 // If mirror or obj is dead, only null-path is taken.
4454 if (stopped()) return true;
4455
4456 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4457 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4458 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4476 CallJavaNode* slow_call = nullptr;
4477 if (uninitialized) {
4478 // Generate optimized virtual call (holder class 'Unsafe' is final)
4479 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4480 } else {
4481 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4482 }
4483 Node* slow_result = set_results_for_java_call(slow_call);
4484 // this->control() comes from set_results_for_java_call
4485 result_reg->set_req(_slow_path, control());
4486 result_val->set_req(_slow_path, slow_result);
4487 result_io ->set_req(_slow_path, i_o());
4488 result_mem->set_req(_slow_path, reset_memory());
4489 }
4490
4491 set_control(normal_ctl);
4492 if (!stopped()) {
4493 // Normal case: The array type has been cached in the java.lang.Class.
4494 // The following call works fine even if the array type is polymorphic.
4495 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4496 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4497 result_reg->init_req(_normal_path, control());
4498 result_val->init_req(_normal_path, obj);
4499 result_io ->init_req(_normal_path, i_o());
4500 result_mem->init_req(_normal_path, reset_memory());
4501
4502 if (uninitialized) {
4503 // Mark the allocation so that zeroing is skipped
4504 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4505 alloc->maybe_set_complete(&_gvn);
4506 }
4507 }
4508
4509 // Return the combined state.
4510 set_i_o( _gvn.transform(result_io) );
4511 set_all_memory( _gvn.transform(result_mem));
4512
4513 C->set_has_split_ifs(true); // Has chance for split-if optimization
4514 set_result(result_reg, result_val);
4515 return true;
4564 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4565 { PreserveReexecuteState preexecs(this);
4566 jvms()->set_should_reexecute(true);
4567
4568 array_type_mirror = null_check(array_type_mirror);
4569 original = null_check(original);
4570
4571 // Check if a null path was taken unconditionally.
4572 if (stopped()) return true;
4573
4574 Node* orig_length = load_array_length(original);
4575
4576 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4577 klass_node = null_check(klass_node);
4578
4579 RegionNode* bailout = new RegionNode(1);
4580 record_for_igvn(bailout);
4581
4582 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4583 // Bail out if that is so.
4584 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4585 if (not_objArray != nullptr) {
4586 // Improve the klass node's type from the new optimistic assumption:
4587 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4588 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4589 Node* cast = new CastPPNode(control(), klass_node, akls);
4590 klass_node = _gvn.transform(cast);
4591 }
4592
4593 // Bail out if either start or end is negative.
4594 generate_negative_guard(start, bailout, &start);
4595 generate_negative_guard(end, bailout, &end);
4596
4597 Node* length = end;
4598 if (_gvn.type(start) != TypeInt::ZERO) {
4599 length = _gvn.transform(new SubINode(end, start));
4600 }
4601
4602 // Bail out if length is negative (i.e., if start > end).
4603 // Without this the new_array would throw
4604 // NegativeArraySizeException but IllegalArgumentException is what
4605 // should be thrown
4606 generate_negative_guard(length, bailout, &length);
4607
4608 // Bail out if start is larger than the original length
4609 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4610 generate_negative_guard(orig_tail, bailout, &orig_tail);
4611
4612 if (bailout->req() > 1) {
4613 PreserveJVMState pjvms(this);
4614 set_control(_gvn.transform(bailout));
4615 uncommon_trap(Deoptimization::Reason_intrinsic,
4616 Deoptimization::Action_maybe_recompile);
4617 }
4618
4619 if (!stopped()) {
4620 // How many elements will we copy from the original?
4621 // The answer is MinI(orig_tail, length).
4622 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4623
4624 // Generate a direct call to the right arraycopy function(s).
4625 // We know the copy is disjoint but we might not know if the
4626 // oop stores need checking.
4627 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4647 }
4648 }
4649
4650 bool validated = false;
4651 // Reason_class_check rather than Reason_intrinsic because we
4652 // want to intrinsify even if this traps.
4653 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4654 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4655
4656 if (not_subtype_ctrl != top()) {
4657 PreserveJVMState pjvms(this);
4658 set_control(not_subtype_ctrl);
4659 uncommon_trap(Deoptimization::Reason_class_check,
4660 Deoptimization::Action_make_not_entrant);
4661 assert(stopped(), "Should be stopped");
4662 }
4663 validated = true;
4664 }
4665
4666 if (!stopped()) {
4667 newcopy = new_array(klass_node, length, 0); // no arguments to push
4668
4669 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4670 load_object_klass(original), klass_node);
4671 if (!is_copyOfRange) {
4672 ac->set_copyof(validated);
4673 } else {
4674 ac->set_copyofrange(validated);
4675 }
4676 Node* n = _gvn.transform(ac);
4677 if (n == ac) {
4678 ac->connect_outputs(this);
4679 } else {
4680 assert(validated, "shouldn't transform if all arguments not validated");
4681 set_all_memory(n);
4682 }
4683 }
4684 }
4685 } // original reexecute is set back here
4686
4687 C->set_has_split_ifs(true); // Has chance for split-if optimization
4719
4720 //-----------------------generate_method_call----------------------------
4721 // Use generate_method_call to make a slow-call to the real
4722 // method if the fast path fails. An alternative would be to
4723 // use a stub like OptoRuntime::slow_arraycopy_Java.
4724 // This only works for expanding the current library call,
4725 // not another intrinsic. (E.g., don't use this for making an
4726 // arraycopy call inside of the copyOf intrinsic.)
4727 CallJavaNode*
4728 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4729 // When compiling the intrinsic method itself, do not use this technique.
4730 guarantee(callee() != C->method(), "cannot make slow-call to self");
4731
4732 ciMethod* method = callee();
4733 // ensure the JVMS we have will be correct for this call
4734 guarantee(method_id == method->intrinsic_id(), "must match");
4735
4736 const TypeFunc* tf = TypeFunc::make(method);
4737 if (res_not_null) {
4738 assert(tf->return_type() == T_OBJECT, "");
4739 const TypeTuple* range = tf->range();
4740 const Type** fields = TypeTuple::fields(range->cnt());
4741 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4742 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4743 tf = TypeFunc::make(tf->domain(), new_range);
4744 }
4745 CallJavaNode* slow_call;
4746 if (is_static) {
4747 assert(!is_virtual, "");
4748 slow_call = new CallStaticJavaNode(C, tf,
4749 SharedRuntime::get_resolve_static_call_stub(), method);
4750 } else if (is_virtual) {
4751 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4752 int vtable_index = Method::invalid_vtable_index;
4753 if (UseInlineCaches) {
4754 // Suppress the vtable call
4755 } else {
4756 // hashCode and clone are not a miranda methods,
4757 // so the vtable index is fixed.
4758 // No need to use the linkResolver to get it.
4759 vtable_index = method->vtable_index();
4760 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4761 "bad index %d", vtable_index);
4762 }
4763 slow_call = new CallDynamicJavaNode(tf,
4780 set_edges_for_java_call(slow_call);
4781 return slow_call;
4782 }
4783
4784
4785 /**
4786 * Build special case code for calls to hashCode on an object. This call may
4787 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4788 * slightly different code.
4789 */
4790 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4791 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4792 assert(!(is_virtual && is_static), "either virtual, special, or static");
4793
4794 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4795
4796 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4797 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4798 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4799 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4800 Node* obj = nullptr;
4801 if (!is_static) {
4802 // Check for hashing null object
4803 obj = null_check_receiver();
4804 if (stopped()) return true; // unconditionally null
4805 result_reg->init_req(_null_path, top());
4806 result_val->init_req(_null_path, top());
4807 } else {
4808 // Do a null check, and return zero if null.
4809 // System.identityHashCode(null) == 0
4810 obj = argument(0);
4811 Node* null_ctl = top();
4812 obj = null_check_oop(obj, &null_ctl);
4813 result_reg->init_req(_null_path, null_ctl);
4814 result_val->init_req(_null_path, _gvn.intcon(0));
4815 }
4816
4817 // Unconditionally null? Then return right away.
4818 if (stopped()) {
4819 set_control( result_reg->in(_null_path));
4820 if (!stopped())
4821 set_result(result_val->in(_null_path));
4822 return true;
4823 }
4824
4825 // We only go to the fast case code if we pass a number of guards. The
4826 // paths which do not pass are accumulated in the slow_region.
4827 RegionNode* slow_region = new RegionNode(1);
4828 record_for_igvn(slow_region);
4829
4830 // If this is a virtual call, we generate a funny guard. We pull out
4831 // the vtable entry corresponding to hashCode() from the target object.
4832 // If the target method which we are calling happens to be the native
4833 // Object hashCode() method, we pass the guard. We do not need this
4834 // guard for non-virtual calls -- the caller is known to be the native
4835 // Object hashCode().
4836 if (is_virtual) {
4837 // After null check, get the object's klass.
4838 Node* obj_klass = load_object_klass(obj);
4839 generate_virtual_guard(obj_klass, slow_region);
4840 }
4841
4842 // Get the header out of the object, use LoadMarkNode when available
4843 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4844 // The control of the load must be null. Otherwise, the load can move before
4845 // the null check after castPP removal.
4846 Node* no_ctrl = nullptr;
4847 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4848
4849 if (!UseObjectMonitorTable) {
4850 // Test the header to see if it is safe to read w.r.t. locking.
4851 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4852 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4853 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4854 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4855 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4856
4857 generate_slow_guard(test_monitor, slow_region);
4858 }
4859
4860 // Get the hash value and check to see that it has been properly assigned.
4861 // We depend on hash_mask being at most 32 bits and avoid the use of
4862 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4863 // vm: see markWord.hpp.
4864 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4865 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4866 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4867 // This hack lets the hash bits live anywhere in the mark object now, as long
4868 // as the shift drops the relevant bits into the low 32 bits. Note that
4869 // Java spec says that HashCode is an int so there's no point in capturing
4870 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4898 // this->control() comes from set_results_for_java_call
4899 result_reg->init_req(_slow_path, control());
4900 result_val->init_req(_slow_path, slow_result);
4901 result_io ->set_req(_slow_path, i_o());
4902 result_mem ->set_req(_slow_path, reset_memory());
4903 }
4904
4905 // Return the combined state.
4906 set_i_o( _gvn.transform(result_io) );
4907 set_all_memory( _gvn.transform(result_mem));
4908
4909 set_result(result_reg, result_val);
4910 return true;
4911 }
4912
4913 //---------------------------inline_native_getClass----------------------------
4914 // public final native Class<?> java.lang.Object.getClass();
4915 //
4916 // Build special case code for calls to getClass on an object.
4917 bool LibraryCallKit::inline_native_getClass() {
4918 Node* obj = null_check_receiver();
4919 if (stopped()) return true;
4920 set_result(load_mirror_from_klass(load_object_klass(obj)));
4921 return true;
4922 }
4923
4924 //-----------------inline_native_Reflection_getCallerClass---------------------
4925 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4926 //
4927 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4928 //
4929 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4930 // in that it must skip particular security frames and checks for
4931 // caller sensitive methods.
4932 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4933 #ifndef PRODUCT
4934 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4935 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4936 }
4937 #endif
4938
5320 // not cloneable or finalizer => slow path to out-of-line Object.clone
5321 //
5322 // The general case has two steps, allocation and copying.
5323 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5324 //
5325 // Copying also has two cases, oop arrays and everything else.
5326 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5327 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5328 //
5329 // These steps fold up nicely if and when the cloned object's klass
5330 // can be sharply typed as an object array, a type array, or an instance.
5331 //
5332 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5333 PhiNode* result_val;
5334
5335 // Set the reexecute bit for the interpreter to reexecute
5336 // the bytecode that invokes Object.clone if deoptimization happens.
5337 { PreserveReexecuteState preexecs(this);
5338 jvms()->set_should_reexecute(true);
5339
5340 Node* obj = null_check_receiver();
5341 if (stopped()) return true;
5342
5343 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5344
5345 // If we are going to clone an instance, we need its exact type to
5346 // know the number and types of fields to convert the clone to
5347 // loads/stores. Maybe a speculative type can help us.
5348 if (!obj_type->klass_is_exact() &&
5349 obj_type->speculative_type() != nullptr &&
5350 obj_type->speculative_type()->is_instance_klass()) {
5351 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5352 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5353 !spec_ik->has_injected_fields()) {
5354 if (!obj_type->isa_instptr() ||
5355 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5356 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5357 }
5358 }
5359 }
5360
5361 // Conservatively insert a memory barrier on all memory slices.
5362 // Do not let writes into the original float below the clone.
5363 insert_mem_bar(Op_MemBarCPUOrder);
5364
5365 // paths into result_reg:
5366 enum {
5367 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5368 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5369 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5370 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5371 PATH_LIMIT
5372 };
5373 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5374 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5375 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5376 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5377 record_for_igvn(result_reg);
5378
5379 Node* obj_klass = load_object_klass(obj);
5380 Node* array_obj = obj;
5381 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5382 if (array_ctl != nullptr) {
5383 // It's an array.
5384 PreserveJVMState pjvms(this);
5385 set_control(array_ctl);
5386 Node* obj_length = load_array_length(array_obj);
5387 Node* array_size = nullptr; // Size of the array without object alignment padding.
5388 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5389
5390 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5391 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5392 // If it is an oop array, it requires very special treatment,
5393 // because gc barriers are required when accessing the array.
5394 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5395 if (is_obja != nullptr) {
5396 PreserveJVMState pjvms2(this);
5397 set_control(is_obja);
5398 // Generate a direct call to the right arraycopy function(s).
5399 // Clones are always tightly coupled.
5400 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5401 ac->set_clone_oop_array();
5402 Node* n = _gvn.transform(ac);
5403 assert(n == ac, "cannot disappear");
5404 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5405
5406 result_reg->init_req(_objArray_path, control());
5407 result_val->init_req(_objArray_path, alloc_obj);
5408 result_i_o ->set_req(_objArray_path, i_o());
5409 result_mem ->set_req(_objArray_path, reset_memory());
5410 }
5411 }
5412 // Otherwise, there are no barriers to worry about.
5413 // (We can dispense with card marks if we know the allocation
5414 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5415 // causes the non-eden paths to take compensating steps to
5416 // simulate a fresh allocation, so that no further
5417 // card marks are required in compiled code to initialize
5418 // the object.)
5419
5420 if (!stopped()) {
5421 copy_to_clone(array_obj, alloc_obj, array_size, true);
5422
5423 // Present the results of the copy.
5424 result_reg->init_req(_array_path, control());
5425 result_val->init_req(_array_path, alloc_obj);
5426 result_i_o ->set_req(_array_path, i_o());
5427 result_mem ->set_req(_array_path, reset_memory());
5428 }
5429 }
5430
5431 // We only go to the instance fast case code if we pass a number of guards.
5432 // The paths which do not pass are accumulated in the slow_region.
5433 RegionNode* slow_region = new RegionNode(1);
5434 record_for_igvn(slow_region);
5435 if (!stopped()) {
5436 // It's an instance (we did array above). Make the slow-path tests.
5437 // If this is a virtual call, we generate a funny guard. We grab
5438 // the vtable entry corresponding to clone() from the target object.
5439 // If the target method which we are calling happens to be the
5440 // Object clone() method, we pass the guard. We do not need this
5441 // guard for non-virtual calls; the caller is known to be the native
5442 // Object clone().
5443 if (is_virtual) {
5444 generate_virtual_guard(obj_klass, slow_region);
5445 }
5446
5447 // The object must be easily cloneable and must not have a finalizer.
5448 // Both of these conditions may be checked in a single test.
5449 // We could optimize the test further, but we don't care.
5450 generate_misc_flags_guard(obj_klass,
5451 // Test both conditions:
5452 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5453 // Must be cloneable but not finalizer:
5454 KlassFlags::_misc_is_cloneable_fast,
5546 set_jvms(sfpt->jvms());
5547 _reexecute_sp = jvms()->sp();
5548
5549 return saved_jvms;
5550 }
5551 }
5552 }
5553 return nullptr;
5554 }
5555
5556 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5557 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5558 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5559 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5560 uint size = alloc->req();
5561 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5562 old_jvms->set_map(sfpt);
5563 for (uint i = 0; i < size; i++) {
5564 sfpt->init_req(i, alloc->in(i));
5565 }
5566 // re-push array length for deoptimization
5567 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5568 old_jvms->set_sp(old_jvms->sp()+1);
5569 old_jvms->set_monoff(old_jvms->monoff()+1);
5570 old_jvms->set_scloff(old_jvms->scloff()+1);
5571 old_jvms->set_endoff(old_jvms->endoff()+1);
5572 old_jvms->set_should_reexecute(true);
5573
5574 sfpt->set_i_o(map()->i_o());
5575 sfpt->set_memory(map()->memory());
5576 sfpt->set_control(map()->control());
5577 return sfpt;
5578 }
5579
5580 // In case of a deoptimization, we restart execution at the
5581 // allocation, allocating a new array. We would leave an uninitialized
5582 // array in the heap that GCs wouldn't expect. Move the allocation
5583 // after the traps so we don't allocate the array if we
5584 // deoptimize. This is possible because tightly_coupled_allocation()
5585 // guarantees there's no observer of the allocated array at this point
5586 // and the control flow is simple enough.
5587 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5588 int saved_reexecute_sp, uint new_idx) {
5589 if (saved_jvms_before_guards != nullptr && !stopped()) {
5590 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5591
5592 assert(alloc != nullptr, "only with a tightly coupled allocation");
5593 // restore JVM state to the state at the arraycopy
5594 saved_jvms_before_guards->map()->set_control(map()->control());
5595 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5596 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5597 // If we've improved the types of some nodes (null check) while
5598 // emitting the guards, propagate them to the current state
5599 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5600 set_jvms(saved_jvms_before_guards);
5601 _reexecute_sp = saved_reexecute_sp;
5602
5603 // Remove the allocation from above the guards
5604 CallProjections callprojs;
5605 alloc->extract_projections(&callprojs, true);
5606 InitializeNode* init = alloc->initialization();
5607 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5608 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5609 init->replace_mem_projs_by(alloc_mem, C);
5610
5611 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5612 // the allocation (i.e. is only valid if the allocation succeeds):
5613 // 1) replace CastIINode with AllocateArrayNode's length here
5614 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5615 //
5616 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5617 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5618 Node* init_control = init->proj_out(TypeFunc::Control);
5619 Node* alloc_length = alloc->Ideal_length();
5620 #ifdef ASSERT
5621 Node* prev_cast = nullptr;
5622 #endif
5623 for (uint i = 0; i < init_control->outcnt(); i++) {
5624 Node* init_out = init_control->raw_out(i);
5625 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5626 #ifdef ASSERT
5627 if (prev_cast == nullptr) {
5628 prev_cast = init_out;
5630 if (prev_cast->cmp(*init_out) == false) {
5631 prev_cast->dump();
5632 init_out->dump();
5633 assert(false, "not equal CastIINode");
5634 }
5635 }
5636 #endif
5637 C->gvn_replace_by(init_out, alloc_length);
5638 }
5639 }
5640 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5641
5642 // move the allocation here (after the guards)
5643 _gvn.hash_delete(alloc);
5644 alloc->set_req(TypeFunc::Control, control());
5645 alloc->set_req(TypeFunc::I_O, i_o());
5646 Node *mem = reset_memory();
5647 set_all_memory(mem);
5648 alloc->set_req(TypeFunc::Memory, mem);
5649 set_control(init->proj_out_or_null(TypeFunc::Control));
5650 set_i_o(callprojs.fallthrough_ioproj);
5651
5652 // Update memory as done in GraphKit::set_output_for_allocation()
5653 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5654 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5655 if (ary_type->isa_aryptr() && length_type != nullptr) {
5656 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5657 }
5658 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5659 int elemidx = C->get_alias_index(telemref);
5660 // Need to properly move every memory projection for the Initialize
5661 #ifdef ASSERT
5662 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5663 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5664 #endif
5665 auto move_proj = [&](ProjNode* proj) {
5666 int alias_idx = C->get_alias_index(proj->adr_type());
5667 assert(alias_idx == Compile::AliasIdxRaw ||
5668 alias_idx == elemidx ||
5669 alias_idx == mark_idx ||
5670 alias_idx == klass_idx, "should be raw memory or array element type");
5980 top_src = src_type->isa_aryptr();
5981 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5982 src_spec = true;
5983 }
5984 if (!has_dest) {
5985 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5986 dest_type = _gvn.type(dest);
5987 top_dest = dest_type->isa_aryptr();
5988 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5989 dest_spec = true;
5990 }
5991 }
5992 }
5993
5994 if (has_src && has_dest && can_emit_guards) {
5995 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5996 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5997 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5998 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5999
6000 if (src_elem == dest_elem && src_elem == T_OBJECT) {
6001 // If both arrays are object arrays then having the exact types
6002 // for both will remove the need for a subtype check at runtime
6003 // before the call and may make it possible to pick a faster copy
6004 // routine (without a subtype check on every element)
6005 // Do we have the exact type of src?
6006 bool could_have_src = src_spec;
6007 // Do we have the exact type of dest?
6008 bool could_have_dest = dest_spec;
6009 ciKlass* src_k = nullptr;
6010 ciKlass* dest_k = nullptr;
6011 if (!src_spec) {
6012 src_k = src_type->speculative_type_not_null();
6013 if (src_k != nullptr && src_k->is_array_klass()) {
6014 could_have_src = true;
6015 }
6016 }
6017 if (!dest_spec) {
6018 dest_k = dest_type->speculative_type_not_null();
6019 if (dest_k != nullptr && dest_k->is_array_klass()) {
6020 could_have_dest = true;
6021 }
6022 }
6023 if (could_have_src && could_have_dest) {
6024 // If we can have both exact types, emit the missing guards
6025 if (could_have_src && !src_spec) {
6026 src = maybe_cast_profiled_obj(src, src_k, true);
6027 }
6028 if (could_have_dest && !dest_spec) {
6029 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6030 }
6031 }
6032 }
6033 }
6034
6035 ciMethod* trap_method = method();
6036 int trap_bci = bci();
6037 if (saved_jvms_before_guards != nullptr) {
6038 trap_method = alloc->jvms()->method();
6039 trap_bci = alloc->jvms()->bci();
6040 }
6041
6042 bool negative_length_guard_generated = false;
6043
6044 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6045 can_emit_guards &&
6046 !src->is_top() && !dest->is_top()) {
6047 // validate arguments: enables transformation the ArrayCopyNode
6048 validated = true;
6049
6050 RegionNode* slow_region = new RegionNode(1);
6051 record_for_igvn(slow_region);
6052
6053 // (1) src and dest are arrays.
6054 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6055 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6056
6057 // (2) src and dest arrays must have elements of the same BasicType
6058 // done at macro expansion or at Ideal transformation time
6059
6060 // (4) src_offset must not be negative.
6061 generate_negative_guard(src_offset, slow_region);
6062
6063 // (5) dest_offset must not be negative.
6064 generate_negative_guard(dest_offset, slow_region);
6065
6066 // (7) src_offset + length must not exceed length of src.
6067 generate_limit_guard(src_offset, length,
6068 load_array_length(src),
6069 slow_region);
6070
6071 // (8) dest_offset + length must not exceed length of dest.
6072 generate_limit_guard(dest_offset, length,
6073 load_array_length(dest),
6074 slow_region);
6075
6076 // (6) length must not be negative.
6077 // This is also checked in generate_arraycopy() during macro expansion, but
6078 // we also have to check it here for the case where the ArrayCopyNode will
6079 // be eliminated by Escape Analysis.
6080 if (EliminateAllocations) {
6081 generate_negative_guard(length, slow_region);
6082 negative_length_guard_generated = true;
6083 }
6084
6085 // (9) each element of an oop array must be assignable
6086 Node* dest_klass = load_object_klass(dest);
6087 if (src != dest) {
6088 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6089
6090 if (not_subtype_ctrl != top()) {
6091 PreserveJVMState pjvms(this);
6092 set_control(not_subtype_ctrl);
6093 uncommon_trap(Deoptimization::Reason_intrinsic,
6094 Deoptimization::Action_make_not_entrant);
6095 assert(stopped(), "Should be stopped");
6096 }
6097 }
6098 {
6099 PreserveJVMState pjvms(this);
6100 set_control(_gvn.transform(slow_region));
6101 uncommon_trap(Deoptimization::Reason_intrinsic,
6102 Deoptimization::Action_make_not_entrant);
6103 assert(stopped(), "Should be stopped");
6104 }
6105
6106 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6107 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6108 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6109 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6110 }
6111
6112 if (stopped()) {
6113 return true;
6114 }
6115
6116 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6117 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6118 // so the compiler has a chance to eliminate them: during macro expansion,
6119 // we have to set their control (CastPP nodes are eliminated).
6120 load_object_klass(src), load_object_klass(dest),
6121 load_array_length(src), load_array_length(dest));
6122
6123 ac->set_arraycopy(validated);
6124
6125 Node* n = _gvn.transform(ac);
6126 if (n == ac) {
6127 ac->connect_outputs(this);
6128 } else {
6129 assert(validated, "shouldn't transform if all arguments not validated");
6130 set_all_memory(n);
6131 }
6132 clear_upper_avx();
6133
6134
6135 return true;
6136 }
6137
6138
6139 // Helper function which determines if an arraycopy immediately follows
6140 // 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);
520 #endif
521 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
522 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
523 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
524 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
525 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
526 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
527 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
528 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
529 case vmIntrinsics::_getLength: return inline_native_getLength();
530 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
531 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
532 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
533 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
534 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
535 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
536 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
537
538 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
539 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
540 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
541 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
542 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
543 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
544 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
545 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
546
547 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
548
549 case vmIntrinsics::_isInstance:
550 case vmIntrinsics::_isHidden:
551 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
552
553 case vmIntrinsics::_floatToRawIntBits:
554 case vmIntrinsics::_floatToIntBits:
555 case vmIntrinsics::_intBitsToFloat:
556 case vmIntrinsics::_doubleToRawLongBits:
557 case vmIntrinsics::_doubleToLongBits:
558 case vmIntrinsics::_longBitsToDouble:
559 case vmIntrinsics::_floatToFloat16:
560 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
561 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
562 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
563 case vmIntrinsics::_floatIsFinite:
564 case vmIntrinsics::_floatIsInfinite:
565 case vmIntrinsics::_doubleIsFinite:
2291 case vmIntrinsics::_remainderUnsigned_l: {
2292 zero_check_long(argument(2));
2293 // Compile-time detect of null-exception
2294 if (stopped()) {
2295 return true; // keep the graph constructed so far
2296 }
2297 n = new UModLNode(control(), argument(0), argument(2));
2298 break;
2299 }
2300 default: fatal_unexpected_iid(id); break;
2301 }
2302 set_result(_gvn.transform(n));
2303 return true;
2304 }
2305
2306 //----------------------------inline_unsafe_access----------------------------
2307
2308 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2309 // Attempt to infer a sharper value type from the offset and base type.
2310 ciKlass* sharpened_klass = nullptr;
2311 bool null_free = false;
2312
2313 // See if it is an instance field, with an object type.
2314 if (alias_type->field() != nullptr) {
2315 if (alias_type->field()->type()->is_klass()) {
2316 sharpened_klass = alias_type->field()->type()->as_klass();
2317 null_free = alias_type->field()->is_null_free();
2318 }
2319 }
2320
2321 const TypeOopPtr* result = nullptr;
2322 // See if it is a narrow oop array.
2323 if (adr_type->isa_aryptr()) {
2324 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2325 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2326 null_free = adr_type->is_aryptr()->is_null_free();
2327 if (elem_type != nullptr && elem_type->is_loaded()) {
2328 // Sharpen the value type.
2329 result = elem_type;
2330 }
2331 }
2332 }
2333
2334 // The sharpened class might be unloaded if there is no class loader
2335 // contraint in place.
2336 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2337 // Sharpen the value type.
2338 result = TypeOopPtr::make_from_klass(sharpened_klass);
2339 if (null_free) {
2340 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2341 }
2342 }
2343 if (result != nullptr) {
2344 #ifndef PRODUCT
2345 if (C->print_intrinsics() || C->print_inlining()) {
2346 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2347 tty->print(" sharpened value: "); result->dump(); tty->cr();
2348 }
2349 #endif
2350 }
2351 return result;
2352 }
2353
2354 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2355 switch (kind) {
2356 case Relaxed:
2357 return MO_UNORDERED;
2358 case Opaque:
2359 return MO_RELAXED;
2360 case Acquire:
2361 return MO_ACQUIRE;
2409 #endif // ASSERT
2410 }
2411 #endif //PRODUCT
2412
2413 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2414
2415 Node* receiver = argument(0); // type: oop
2416
2417 // Build address expression.
2418 Node* heap_base_oop = top();
2419
2420 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2421 Node* base = argument(1); // type: oop
2422 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2423 Node* offset = argument(2); // type: long
2424 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2425 // to be plain byte offsets, which are also the same as those accepted
2426 // by oopDesc::field_addr.
2427 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2428 "fieldOffset must be byte-scaled");
2429
2430 if (base->is_InlineType()) {
2431 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2432 InlineTypeNode* vt = base->as_InlineType();
2433 if (offset->is_Con()) {
2434 long off = find_long_con(offset, 0);
2435 ciInlineKlass* vk = vt->type()->inline_klass();
2436 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2437 return false;
2438 }
2439
2440 ciField* field = vk->get_non_flat_field_by_offset(off);
2441 if (field != nullptr) {
2442 BasicType bt = type2field[field->type()->basic_type()];
2443 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2444 bt = T_OBJECT;
2445 }
2446 if (bt == type && !field->is_flat()) {
2447 Node* value = vt->field_value_by_offset(off, false);
2448 const Type* value_type = _gvn.type(value);
2449 if (value_type->is_inlinetypeptr()) {
2450 value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2451 }
2452 set_result(value);
2453 return true;
2454 }
2455 }
2456 }
2457 {
2458 // Re-execute the unsafe access if allocation triggers deoptimization.
2459 PreserveReexecuteState preexecs(this);
2460 jvms()->set_should_reexecute(true);
2461 vt = vt->buffer(this);
2462 }
2463 base = vt->get_oop();
2464 }
2465
2466 // 32-bit machines ignore the high half!
2467 offset = ConvL2X(offset);
2468
2469 // Save state and restore on bailout
2470 SavedState old_state(this);
2471
2472 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2473 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2474
2475 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2476 if (type != T_OBJECT) {
2477 decorators |= IN_NATIVE; // off-heap primitive access
2478 } else {
2479 return false; // off-heap oop accesses are not supported
2480 }
2481 } else {
2482 heap_base_oop = base; // on-heap or mixed access
2483 }
2484
2485 // Can base be null? Otherwise, always on-heap access.
2489 decorators |= IN_HEAP;
2490 }
2491
2492 Node* val = is_store ? argument(4) : nullptr;
2493
2494 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2495 if (adr_type == TypePtr::NULL_PTR) {
2496 return false; // off-heap access with zero address
2497 }
2498
2499 // Try to categorize the address.
2500 Compile::AliasType* alias_type = C->alias_type(adr_type);
2501 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2502
2503 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2504 alias_type->adr_type() == TypeAryPtr::RANGE) {
2505 return false; // not supported
2506 }
2507
2508 bool mismatched = false;
2509 BasicType bt = T_ILLEGAL;
2510 ciField* field = nullptr;
2511 if (adr_type->isa_instptr()) {
2512 const TypeInstPtr* instptr = adr_type->is_instptr();
2513 ciInstanceKlass* k = instptr->instance_klass();
2514 int off = instptr->offset();
2515 if (instptr->const_oop() != nullptr &&
2516 k == ciEnv::current()->Class_klass() &&
2517 instptr->offset() >= (k->size_helper() * wordSize)) {
2518 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2519 field = k->get_field_by_offset(off, true);
2520 } else {
2521 field = k->get_non_flat_field_by_offset(off);
2522 }
2523 if (field != nullptr) {
2524 bt = type2field[field->type()->basic_type()];
2525 }
2526 if (bt != alias_type->basic_type()) {
2527 // Type mismatch. Is it an access to a nested flat field?
2528 field = k->get_field_by_offset(off, false);
2529 if (field != nullptr) {
2530 bt = type2field[field->type()->basic_type()];
2531 }
2532 }
2533 assert(bt == alias_type->basic_type(), "should match");
2534 } else {
2535 bt = alias_type->basic_type();
2536 }
2537
2538 if (bt != T_ILLEGAL) {
2539 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2540 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2541 // Alias type doesn't differentiate between byte[] and boolean[]).
2542 // Use address type to get the element type.
2543 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2544 }
2545 if (is_reference_type(bt, true)) {
2546 // accessing an array field with getReference is not a mismatch
2547 bt = T_OBJECT;
2548 }
2549 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2550 // Don't intrinsify mismatched object accesses
2551 return false;
2552 }
2553 mismatched = (bt != type);
2554 } else if (alias_type->adr_type()->isa_oopptr()) {
2555 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2556 }
2557
2558 old_state.discard();
2559 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2560
2561 if (mismatched) {
2562 decorators |= C2_MISMATCHED;
2563 }
2564
2565 // First guess at the value type.
2566 const Type *value_type = Type::get_const_basic_type(type);
2567
2568 // Figure out the memory ordering.
2569 decorators |= mo_decorator_for_access_kind(kind);
2570
2571 if (!is_store) {
2572 if (type == T_OBJECT) {
2573 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2574 if (tjp != nullptr) {
2575 value_type = tjp;
2576 }
2577 }
2578 }
2579
2580 receiver = null_check(receiver);
2581 if (stopped()) {
2582 return true;
2583 }
2584 // Heap pointers get a null-check from the interpreter,
2585 // as a courtesy. However, this is not guaranteed by Unsafe,
2586 // and it is not possible to fully distinguish unintended nulls
2587 // from intended ones in this API.
2588
2589 if (!is_store) {
2590 Node* p = nullptr;
2591 // Try to constant fold a load from a constant field
2592
2593 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2594 // final or stable field
2595 p = make_constant_from_field(field, heap_base_oop);
2596 }
2597
2598 if (p == nullptr) { // Could not constant fold the load
2599 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2600 const TypeOopPtr* ptr = value_type->make_oopptr();
2601 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2602 // Load a non-flattened inline type from memory
2603 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2604 }
2605 // Normalize the value returned by getBoolean in the following cases
2606 if (type == T_BOOLEAN &&
2607 (mismatched ||
2608 heap_base_oop == top() || // - heap_base_oop is null or
2609 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2610 // and the unsafe access is made to large offset
2611 // (i.e., larger than the maximum offset necessary for any
2612 // field access)
2613 ) {
2614 IdealKit ideal = IdealKit(this);
2615 #define __ ideal.
2616 IdealVariable normalized_result(ideal);
2617 __ declarations_done();
2618 __ set(normalized_result, p);
2619 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2620 __ set(normalized_result, ideal.ConI(1));
2621 ideal.end_if();
2622 final_sync(ideal);
2623 p = __ value(normalized_result);
2624 #undef __
2628 p = gvn().transform(new CastP2XNode(nullptr, p));
2629 p = ConvX2UL(p);
2630 }
2631 // The load node has the control of the preceding MemBarCPUOrder. All
2632 // following nodes will have the control of the MemBarCPUOrder inserted at
2633 // the end of this method. So, pushing the load onto the stack at a later
2634 // point is fine.
2635 set_result(p);
2636 } else {
2637 if (bt == T_ADDRESS) {
2638 // Repackage the long as a pointer.
2639 val = ConvL2X(val);
2640 val = gvn().transform(new CastX2PNode(val));
2641 }
2642 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2643 }
2644
2645 return true;
2646 }
2647
2648 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2649 #ifdef ASSERT
2650 {
2651 ResourceMark rm;
2652 // Check the signatures.
2653 ciSignature* sig = callee()->signature();
2654 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2655 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2656 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2657 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2658 if (is_store) {
2659 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2660 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2661 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2662 } else {
2663 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2664 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2665 }
2666 }
2667 #endif // ASSERT
2668
2669 assert(kind == Relaxed, "Only plain accesses for now");
2670 if (callee()->is_static()) {
2671 // caller must have the capability!
2672 return false;
2673 }
2674 C->set_has_unsafe_access(true);
2675
2676 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2677 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2678 // parameter valueType is not a constant
2679 return false;
2680 }
2681 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2682 if (!mirror_type->is_inlinetype()) {
2683 // Dead code
2684 return false;
2685 }
2686 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2687
2688 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2689 if (layout_type == nullptr || !layout_type->is_con()) {
2690 // parameter layoutKind is not a constant
2691 return false;
2692 }
2693 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2694 layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2695 "invalid layoutKind %d", layout_type->get_con());
2696 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2697 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2698 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2699 "unexpected layoutKind %d", layout_type->get_con());
2700
2701 null_check(argument(0));
2702 if (stopped()) {
2703 return true;
2704 }
2705
2706 Node* base = must_be_not_null(argument(1), true);
2707 Node* offset = argument(2);
2708 const Type* base_type = _gvn.type(base);
2709
2710 Node* ptr;
2711 bool immutable_memory = false;
2712 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2713 if (base_type->isa_instptr()) {
2714 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2715 if (offset_type == nullptr || !offset_type->is_con()) {
2716 // Offset into a non-array should be a constant
2717 decorators |= C2_MISMATCHED;
2718 } else {
2719 int offset_con = checked_cast<int>(offset_type->get_con());
2720 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2721 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2722 if (field == nullptr) {
2723 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2724 decorators |= C2_MISMATCHED;
2725 } else {
2726 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2727 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2728 immutable_memory = field->is_strict() && field->is_final();
2729
2730 if (base->is_InlineType()) {
2731 assert(!is_store, "Cannot store into a non-larval value object");
2732 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2733 return true;
2734 }
2735 }
2736 }
2737
2738 if (base->is_InlineType()) {
2739 assert(!is_store, "Cannot store into a non-larval value object");
2740 base = base->as_InlineType()->buffer(this, true);
2741 }
2742 ptr = basic_plus_adr(base, ConvL2X(offset));
2743 } else if (base_type->isa_aryptr()) {
2744 decorators |= IS_ARRAY;
2745 if (layout == LayoutKind::REFERENCE) {
2746 if (!base_type->is_aryptr()->is_not_flat()) {
2747 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2748 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2749 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2750 replace_in_map(base, new_base);
2751 base = new_base;
2752 }
2753 ptr = basic_plus_adr(base, ConvL2X(offset));
2754 } else {
2755 if (UseArrayFlattening) {
2756 // Flat array must have an exact type
2757 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2758 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2759 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2760 replace_in_map(base, new_base);
2761 base = new_base;
2762 ptr = basic_plus_adr(base, ConvL2X(offset));
2763 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2764 if (ptr_type->field_offset().get() != 0) {
2765 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2766 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2767 }
2768 } else {
2769 uncommon_trap(Deoptimization::Reason_intrinsic,
2770 Deoptimization::Action_none);
2771 return true;
2772 }
2773 }
2774 } else {
2775 decorators |= C2_MISMATCHED;
2776 ptr = basic_plus_adr(base, ConvL2X(offset));
2777 }
2778
2779 if (is_store) {
2780 Node* value = argument(6);
2781 const Type* value_type = _gvn.type(value);
2782 if (!value_type->is_inlinetypeptr()) {
2783 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2784 Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2785 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2786 replace_in_map(value, new_value);
2787 value = new_value;
2788 }
2789
2790 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());
2791 if (layout == LayoutKind::REFERENCE) {
2792 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2793 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2794 } else {
2795 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2796 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2797 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2798 }
2799
2800 return true;
2801 } else {
2802 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2803 InlineTypeNode* result;
2804 if (layout == LayoutKind::REFERENCE) {
2805 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2806 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2807 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2808 } else {
2809 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2810 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2811 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2812 }
2813
2814 set_result(result);
2815 return true;
2816 }
2817 }
2818
2819 //----------------------------inline_unsafe_load_store----------------------------
2820 // This method serves a couple of different customers (depending on LoadStoreKind):
2821 //
2822 // LS_cmp_swap:
2823 //
2824 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2825 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2826 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2827 //
2828 // LS_cmp_swap_weak:
2829 //
2830 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2831 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2832 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2833 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2834 //
2835 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2836 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2837 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2838 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3001 }
3002 case LS_cmp_swap:
3003 case LS_cmp_swap_weak:
3004 case LS_get_add:
3005 break;
3006 default:
3007 ShouldNotReachHere();
3008 }
3009
3010 // Null check receiver.
3011 receiver = null_check(receiver);
3012 if (stopped()) {
3013 return true;
3014 }
3015
3016 int alias_idx = C->get_alias_index(adr_type);
3017
3018 if (is_reference_type(type)) {
3019 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3020
3021 if (oldval != nullptr && oldval->is_InlineType()) {
3022 // Re-execute the unsafe access if allocation triggers deoptimization.
3023 PreserveReexecuteState preexecs(this);
3024 jvms()->set_should_reexecute(true);
3025 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3026 }
3027 if (newval != nullptr && newval->is_InlineType()) {
3028 // Re-execute the unsafe access if allocation triggers deoptimization.
3029 PreserveReexecuteState preexecs(this);
3030 jvms()->set_should_reexecute(true);
3031 newval = newval->as_InlineType()->buffer(this)->get_oop();
3032 }
3033
3034 // Transformation of a value which could be null pointer (CastPP #null)
3035 // could be delayed during Parse (for example, in adjust_map_after_if()).
3036 // Execute transformation here to avoid barrier generation in such case.
3037 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3038 newval = _gvn.makecon(TypePtr::NULL_PTR);
3039
3040 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3041 // Refine the value to a null constant, when it is known to be null
3042 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3043 }
3044 }
3045
3046 Node* result = nullptr;
3047 switch (kind) {
3048 case LS_cmp_exchange: {
3049 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3050 oldval, newval, value_type, type, decorators);
3051 break;
3052 }
3053 case LS_cmp_swap_weak:
3082 insert_mem_bar(Op_MemBarCPUOrder);
3083 switch(id) {
3084 case vmIntrinsics::_loadFence:
3085 insert_mem_bar(Op_LoadFence);
3086 return true;
3087 case vmIntrinsics::_storeFence:
3088 insert_mem_bar(Op_StoreFence);
3089 return true;
3090 case vmIntrinsics::_storeStoreFence:
3091 insert_mem_bar(Op_StoreStoreFence);
3092 return true;
3093 case vmIntrinsics::_fullFence:
3094 insert_mem_bar(Op_MemBarFull);
3095 return true;
3096 default:
3097 fatal_unexpected_iid(id);
3098 return false;
3099 }
3100 }
3101
3102 // private native int arrayInstanceBaseOffset0(Object[] array);
3103 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3104 Node* array = argument(1);
3105 Node* klass_node = load_object_klass(array);
3106
3107 jint layout_con = Klass::_lh_neutral_value;
3108 Node* layout_val = get_layout_helper(klass_node, layout_con);
3109 int layout_is_con = (layout_val == nullptr);
3110
3111 Node* header_size = nullptr;
3112 if (layout_is_con) {
3113 int hsize = Klass::layout_helper_header_size(layout_con);
3114 header_size = intcon(hsize);
3115 } else {
3116 Node* hss = intcon(Klass::_lh_header_size_shift);
3117 Node* hsm = intcon(Klass::_lh_header_size_mask);
3118 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3119 header_size = _gvn.transform(new AndINode(header_size, hsm));
3120 }
3121 set_result(header_size);
3122 return true;
3123 }
3124
3125 // private native int arrayInstanceIndexScale0(Object[] array);
3126 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3127 Node* array = argument(1);
3128 Node* klass_node = load_object_klass(array);
3129
3130 jint layout_con = Klass::_lh_neutral_value;
3131 Node* layout_val = get_layout_helper(klass_node, layout_con);
3132 int layout_is_con = (layout_val == nullptr);
3133
3134 Node* element_size = nullptr;
3135 if (layout_is_con) {
3136 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3137 int elem_size = 1 << log_element_size;
3138 element_size = intcon(elem_size);
3139 } else {
3140 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3141 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3142 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3143 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3144 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3145 }
3146 set_result(element_size);
3147 return true;
3148 }
3149
3150 // private native int arrayLayout0(Object[] array);
3151 bool LibraryCallKit::inline_arrayLayout() {
3152 RegionNode* region = new RegionNode(2);
3153 Node* phi = new PhiNode(region, TypeInt::POS);
3154
3155 Node* array = argument(1);
3156 Node* klass_node = load_object_klass(array);
3157 generate_refArray_guard(klass_node, region);
3158 if (region->req() == 3) {
3159 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3160 }
3161
3162 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3163 Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3164 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3165
3166 region->init_req(1, control());
3167 phi->init_req(1, layout_kind);
3168
3169 set_control(_gvn.transform(region));
3170 set_result(_gvn.transform(phi));
3171 return true;
3172 }
3173
3174 // private native int[] getFieldMap0(Class <?> c);
3175 // int offset = c._klass._acmp_maps_offset;
3176 // return (int[])c.obj_field(offset);
3177 bool LibraryCallKit::inline_getFieldMap() {
3178 Node* mirror = argument(1);
3179 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3180
3181 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3182 Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3183 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3184 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3185
3186 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3187 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3188 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3189
3190 set_result(map);
3191 return true;
3192 }
3193
3194 bool LibraryCallKit::inline_onspinwait() {
3195 insert_mem_bar(Op_OnSpinWait);
3196 return true;
3197 }
3198
3199 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3200 if (!kls->is_Con()) {
3201 return true;
3202 }
3203 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3204 if (klsptr == nullptr) {
3205 return true;
3206 }
3207 ciInstanceKlass* ik = klsptr->instance_klass();
3208 // don't need a guard for a klass that is already initialized
3209 return !ik->is_initialized();
3210 }
3211
3212 //----------------------------inline_unsafe_writeback0-------------------------
3213 // public native void Unsafe.writeback0(long address)
3292 Deoptimization::Action_make_not_entrant);
3293 }
3294 if (stopped()) {
3295 return true;
3296 }
3297 #endif //INCLUDE_JVMTI
3298
3299 Node* test = nullptr;
3300 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3301 // Note: The argument might still be an illegal value like
3302 // Serializable.class or Object[].class. The runtime will handle it.
3303 // But we must make an explicit check for initialization.
3304 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3305 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3306 // can generate code to load it as unsigned byte.
3307 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3308 Node* bits = intcon(InstanceKlass::fully_initialized);
3309 test = _gvn.transform(new SubINode(inst, bits));
3310 // The 'test' is non-zero if we need to take a slow path.
3311 }
3312 Node* obj = new_instance(kls, test);
3313 set_result(obj);
3314 return true;
3315 }
3316
3317 //------------------------inline_native_time_funcs--------------
3318 // inline code for System.currentTimeMillis() and System.nanoTime()
3319 // these have the same type and signature
3320 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3321 const TypeFunc* tf = OptoRuntime::void_long_Type();
3322 const TypePtr* no_memory_effects = nullptr;
3323 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3324 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3325 #ifdef ASSERT
3326 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3327 assert(value_top == top(), "second value must be top");
3328 #endif
3329 set_result(value);
3330 return true;
3331 }
4222 Node* arr = argument(1);
4223 Node* thread = _gvn.transform(new ThreadLocalNode());
4224 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4225 Node* thread_obj_handle
4226 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4227 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4228 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4229
4230 // Change the _monitor_owner_id of the JavaThread
4231 Node* tid = load_field_from_object(arr, "tid", "J");
4232 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4233 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4234
4235 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4236 return true;
4237 }
4238
4239 const Type* LibraryCallKit::scopedValueCache_type() {
4240 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4241 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4242 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4243
4244 // Because we create the scopedValue cache lazily we have to make the
4245 // type of the result BotPTR.
4246 bool xk = etype->klass_is_exact();
4247 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4248 return objects_type;
4249 }
4250
4251 Node* LibraryCallKit::scopedValueCache_helper() {
4252 Node* thread = _gvn.transform(new ThreadLocalNode());
4253 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4254 // We cannot use immutable_memory() because we might flip onto a
4255 // different carrier thread, at which point we'll need to use that
4256 // carrier thread's cache.
4257 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4258 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4259 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4260 }
4261
4262 //------------------------inline_native_scopedValueCache------------------
4263 bool LibraryCallKit::inline_native_scopedValueCache() {
4264 Node* cache_obj_handle = scopedValueCache_helper();
4265 const Type* objects_type = scopedValueCache_type();
4266 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4267
4403 }
4404 return kls;
4405 }
4406
4407 //--------------------(inline_native_Class_query helpers)---------------------
4408 // Use this for JVM_ACC_INTERFACE.
4409 // Fall through if (mods & mask) == bits, take the guard otherwise.
4410 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4411 ByteSize offset, const Type* type, BasicType bt) {
4412 // Branch around if the given klass has the given modifier bit set.
4413 // Like generate_guard, adds a new path onto the region.
4414 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4415 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4416 Node* mask = intcon(modifier_mask);
4417 Node* bits = intcon(modifier_bits);
4418 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4419 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4420 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4421 return generate_fair_guard(bol, region);
4422 }
4423
4424 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4425 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4426 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4427 }
4428
4429 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4430 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4431 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4432 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4433 }
4434
4435 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4436 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4437 }
4438
4439 //-------------------------inline_native_Class_query-------------------
4440 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4441 const Type* return_type = TypeInt::BOOL;
4442 Node* prim_return_value = top(); // what happens if it's a primitive class?
4443 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4529
4530
4531 case vmIntrinsics::_getSuperclass:
4532 // The rules here are somewhat unfortunate, but we can still do better
4533 // with random logic than with a JNI call.
4534 // Interfaces store null or Object as _super, but must report null.
4535 // Arrays store an intermediate super as _super, but must report Object.
4536 // Other types can report the actual _super.
4537 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4538 if (generate_array_guard(kls, region) != nullptr) {
4539 // A guard was added. If the guard is taken, it was an array.
4540 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4541 }
4542 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4543 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4544 if (generate_interface_guard(kls, region) != nullptr) {
4545 // A guard was added. If the guard is taken, it was an interface.
4546 phi->add_req(null());
4547 }
4548 // If we fall through, it's a plain class. Get its _super.
4549 if (!stopped()) {
4550 p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4551 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4552 null_ctl = top();
4553 kls = null_check_oop(kls, &null_ctl);
4554 if (null_ctl != top()) {
4555 // If the guard is taken, Object.superClass is null (both klass and mirror).
4556 region->add_req(null_ctl);
4557 phi ->add_req(null());
4558 }
4559 if (!stopped()) {
4560 query_value = load_mirror_from_klass(kls);
4561 }
4562 }
4563 break;
4564
4565 default:
4566 fatal_unexpected_iid(id);
4567 break;
4568 }
4569
4570 // Fall-through is the normal case of a query to a real class.
4571 phi->init_req(1, query_value);
4572 region->init_req(1, control());
4573
4574 C->set_has_split_ifs(true); // Has chance for split-if optimization
4575 set_result(region, phi);
4576 return true;
4577 }
4578
4579
4580 //-------------------------inline_Class_cast-------------------
4581 bool LibraryCallKit::inline_Class_cast() {
4582 Node* mirror = argument(0); // Class
4583 Node* obj = argument(1);
4584 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4585 if (mirror_con == nullptr) {
4586 return false; // dead path (mirror->is_top()).
4587 }
4588 if (obj == nullptr || obj->is_top()) {
4589 return false; // dead path
4590 }
4591 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4592
4593 // First, see if Class.cast() can be folded statically.
4594 // java_mirror_type() returns non-null for compile-time Class constants.
4595 ciType* tm = mirror_con->java_mirror_type();
4596 if (tm != nullptr && tm->is_klass() &&
4597 tp != nullptr) {
4598 if (!tp->is_loaded()) {
4599 // Don't use intrinsic when class is not loaded.
4600 return false;
4601 } else {
4602 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4603 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4604 if (static_res == Compile::SSC_always_true) {
4605 // isInstance() is true - fold the code.
4606 set_result(obj);
4607 return true;
4608 } else if (static_res == Compile::SSC_always_false) {
4609 // Don't use intrinsic, have to throw ClassCastException.
4610 // If the reference is null, the non-intrinsic bytecode will
4611 // be optimized appropriately.
4612 return false;
4613 }
4614 }
4615 }
4616
4617 // Bailout intrinsic and do normal inlining if exception path is frequent.
4618 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4619 return false;
4620 }
4621
4622 // Generate dynamic checks.
4623 // Class.cast() is java implementation of _checkcast bytecode.
4624 // Do checkcast (Parse::do_checkcast()) optimizations here.
4625
4626 mirror = null_check(mirror);
4627 // If mirror is dead, only null-path is taken.
4628 if (stopped()) {
4629 return true;
4630 }
4631
4632 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4633 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4634 RegionNode* region = new RegionNode(PATH_LIMIT);
4635 record_for_igvn(region);
4636
4637 // Now load the mirror's klass metaobject, and null-check it.
4638 // If kls is null, we have a primitive mirror and
4639 // nothing is an instance of a primitive type.
4640 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4641
4642 Node* res = top();
4643 Node* io = i_o();
4644 Node* mem = merged_memory();
4645 SafePointNode* new_cast_failure_map = nullptr;
4646
4647 if (!stopped()) {
4648
4649 Node* bad_type_ctrl = top();
4650 // Do checkcast optimizations.
4651 res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4652 region->init_req(_bad_type_path, bad_type_ctrl);
4653 }
4654 if (region->in(_prim_path) != top() ||
4655 region->in(_bad_type_path) != top() ||
4656 region->in(_npe_path) != top()) {
4657 // Let Interpreter throw ClassCastException.
4658 PreserveJVMState pjvms(this);
4659 if (new_cast_failure_map != nullptr) {
4660 // The current map on the success path could have been modified. Use the dedicated failure path map.
4661 set_map(new_cast_failure_map);
4662 }
4663 set_control(_gvn.transform(region));
4664 // Set IO and memory because gen_checkcast may override them when buffering inline types
4665 set_i_o(io);
4666 set_all_memory(mem);
4667 uncommon_trap(Deoptimization::Reason_intrinsic,
4668 Deoptimization::Action_maybe_recompile);
4669 }
4670 if (!stopped()) {
4671 set_result(res);
4672 }
4673 return true;
4674 }
4675
4676
4677 //--------------------------inline_native_subtype_check------------------------
4678 // This intrinsic takes the JNI calls out of the heart of
4679 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4680 bool LibraryCallKit::inline_native_subtype_check() {
4681 // Pull both arguments off the stack.
4682 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4683 args[0] = argument(0);
4684 args[1] = argument(1);
4685 Node* klasses[2]; // corresponding Klasses: superk, subk
4686 klasses[0] = klasses[1] = top();
4687
4688 enum {
4689 // A full decision tree on {superc is prim, subc is prim}:
4690 _prim_0_path = 1, // {P,N} => false
4691 // {P,P} & superc!=subc => false
4692 _prim_same_path, // {P,P} & superc==subc => true
4693 _prim_1_path, // {N,P} => false
4694 _ref_subtype_path, // {N,N} & subtype check wins => true
4695 _both_ref_path, // {N,N} & subtype check loses => false
4696 PATH_LIMIT
4697 };
4698
4699 RegionNode* region = new RegionNode(PATH_LIMIT);
4700 RegionNode* prim_region = new RegionNode(2);
4701 Node* phi = new PhiNode(region, TypeInt::BOOL);
4702 record_for_igvn(region);
4703 record_for_igvn(prim_region);
4704
4705 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4706 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4707 int class_klass_offset = java_lang_Class::klass_offset();
4708
4709 // First null-check both mirrors and load each mirror's klass metaobject.
4710 int which_arg;
4711 for (which_arg = 0; which_arg <= 1; which_arg++) {
4712 Node* arg = args[which_arg];
4713 arg = null_check(arg);
4714 if (stopped()) break;
4715 args[which_arg] = arg;
4716
4717 Node* p = basic_plus_adr(arg, class_klass_offset);
4718 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4719 klasses[which_arg] = _gvn.transform(kls);
4720 }
4721
4722 // Having loaded both klasses, test each for null.
4723 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4724 for (which_arg = 0; which_arg <= 1; which_arg++) {
4725 Node* kls = klasses[which_arg];
4726 Node* null_ctl = top();
4727 kls = null_check_oop(kls, &null_ctl, never_see_null);
4728 if (which_arg == 0) {
4729 prim_region->init_req(1, null_ctl);
4730 } else {
4731 region->init_req(_prim_1_path, null_ctl);
4732 }
4733 if (stopped()) break;
4734 klasses[which_arg] = kls;
4735 }
4736
4737 if (!stopped()) {
4738 // now we have two reference types, in klasses[0..1]
4739 Node* subk = klasses[1]; // the argument to isAssignableFrom
4740 Node* superk = klasses[0]; // the receiver
4741 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4742 region->set_req(_ref_subtype_path, control());
4743 }
4744
4745 // If both operands are primitive (both klasses null), then
4746 // we must return true when they are identical primitives.
4747 // It is convenient to test this after the first null klass check.
4748 // This path is also used if superc is a value mirror.
4749 set_control(_gvn.transform(prim_region));
4750 if (!stopped()) {
4751 // Since superc is primitive, make a guard for the superc==subc case.
4752 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4753 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4754 generate_fair_guard(bol_eq, region);
4755 if (region->req() == PATH_LIMIT+1) {
4756 // A guard was added. If the added guard is taken, superc==subc.
4757 region->swap_edges(PATH_LIMIT, _prim_same_path);
4758 region->del_req(PATH_LIMIT);
4759 }
4760 region->set_req(_prim_0_path, control()); // Not equal after all.
4761 }
4762
4763 // these are the only paths that produce 'true':
4764 phi->set_req(_prim_same_path, intcon(1));
4765 phi->set_req(_ref_subtype_path, intcon(1));
4766
4767 // pull together the cases:
4768 assert(region->req() == PATH_LIMIT, "sane region");
4769 for (uint i = 1; i < region->req(); i++) {
4770 Node* ctl = region->in(i);
4771 if (ctl == nullptr || ctl == top()) {
4772 region->set_req(i, top());
4773 phi ->set_req(i, top());
4774 } else if (phi->in(i) == nullptr) {
4775 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4776 }
4777 }
4778
4779 set_control(_gvn.transform(region));
4780 set_result(_gvn.transform(phi));
4781 return true;
4782 }
4783
4784 //---------------------generate_array_guard_common------------------------
4785 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4786
4787 if (stopped()) {
4788 return nullptr;
4789 }
4790
4791 // Like generate_guard, adds a new path onto the region.
4792 jint layout_con = 0;
4793 Node* layout_val = get_layout_helper(kls, layout_con);
4794 if (layout_val == nullptr) {
4795 bool query = 0;
4796 switch(kind) {
4797 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4798 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4799 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4800 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4801 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4802 default:
4803 ShouldNotReachHere();
4804 }
4805 if (!query) {
4806 return nullptr; // never a branch
4807 } else { // always a branch
4808 Node* always_branch = control();
4809 if (region != nullptr)
4810 region->add_req(always_branch);
4811 set_control(top());
4812 return always_branch;
4813 }
4814 }
4815 unsigned int value = 0;
4816 BoolTest::mask btest = BoolTest::illegal;
4817 switch(kind) {
4818 case RefArray:
4819 case NonRefArray: {
4820 value = Klass::_lh_array_tag_ref_value;
4821 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4822 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4823 break;
4824 }
4825 case TypeArray: {
4826 value = Klass::_lh_array_tag_type_value;
4827 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4828 btest = BoolTest::eq;
4829 break;
4830 }
4831 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4832 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4833 default:
4834 ShouldNotReachHere();
4835 }
4836 // Now test the correct condition.
4837 jint nval = (jint)value;
4838 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4839 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4840 Node* ctrl = generate_fair_guard(bol, region);
4841 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4842 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4843 // Keep track of the fact that 'obj' is an array to prevent
4844 // array specific accesses from floating above the guard.
4845 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4846 }
4847 return ctrl;
4848 }
4849
4850 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4851 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4852 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4853 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4854 assert(null_free || atomic, "nullable implies atomic");
4855 Node* componentType = argument(0);
4856 Node* length = argument(1);
4857 Node* init_val = null_free ? argument(2) : nullptr;
4858
4859 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4860 if (tp != nullptr) {
4861 ciInstanceKlass* ik = tp->instance_klass();
4862 if (ik == C->env()->Class_klass()) {
4863 ciType* t = tp->java_mirror_type();
4864 if (t != nullptr && t->is_inlinetype()) {
4865
4866 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4867 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4868
4869 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4870 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4871 return false;
4872 }
4873
4874 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4875 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4876 if (null_free) {
4877 if (init_val->is_InlineType()) {
4878 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4879 // Zeroing is enough because the init value is the all-zero value
4880 init_val = nullptr;
4881 } else {
4882 init_val = init_val->as_InlineType()->buffer(this);
4883 }
4884 }
4885 if (init_val != nullptr) {
4886 #ifdef ASSERT
4887 init_val = null_check(init_val);
4888 Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4889 {
4890 PreserveJVMState pjvms(this);
4891 set_control(wrong_type_ctl);
4892 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4893 stop_and_kill_map();
4894 }
4895 #endif
4896 init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4897 }
4898 }
4899 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4900 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4901 assert(arytype->is_null_free() == null_free, "inconsistency");
4902 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4903 set_result(obj);
4904 return true;
4905 }
4906 }
4907 }
4908 }
4909 return false;
4910 }
4911
4912 // public static native boolean ValueClass::isFlatArray(Object array);
4913 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4914 // public static native boolean ValueClass::isAtomicArray(Object array);
4915 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4916 Node* array = argument(0);
4917
4918 Node* bol;
4919 switch(check) {
4920 case IsFlat:
4921 bol = flat_array_test(load_object_klass(array));
4922 break;
4923 case IsNullRestricted:
4924 bol = null_free_array_test(array);
4925 break;
4926 case IsAtomic: {
4927 // See conditions in JVM_IsAtomicArray
4928 // 1. If not flat, then atomic, or else...
4929 RegionNode* atomic_region = new RegionNode(1);
4930 RegionNode* non_atomic_region = new RegionNode(1);
4931 Node* array_klass = load_object_klass(array);
4932 Node* is_flat_bol = flat_array_test(array_klass);
4933 IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
4934 atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
4935 set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
4936
4937 // 2. ...if the layout is atomic, then atomic, or else...
4938 Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
4939
4940 // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
4941 int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4942 Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
4943 Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
4944 int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
4945 Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
4946 Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
4947
4948 // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
4949 Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
4950 Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
4951 IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
4952 Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
4953 Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
4954
4955 Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
4956 Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
4957 Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
4958 IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
4959 Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
4960 Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
4961 atomic_region->add_req(is_naturally_atomic_ctl);
4962 non_atomic_region->add_req(is_not_naturally_atomic_ctl);
4963
4964 Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
4965 Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
4966 Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
4967 IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
4968 Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
4969 Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
4970 atomic_region->add_req(is_empty_inline_type_ctl);
4971 non_atomic_region->add_req(is_nonempty_inline_type_ctl);
4972
4973 // ...non-atomic, but we tried everything.
4974 RegionNode* decision = new RegionNode(3);
4975 decision->set_req(1, _gvn.transform(atomic_region));
4976 decision->set_req(2, _gvn.transform(non_atomic_region));
4977 PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
4978 result->set_req(2, intcon(0));
4979 set_control(_gvn.transform(decision));
4980 set_result(_gvn.transform(result));
4981 return true;
4982 }
4983 default:
4984 ShouldNotReachHere();
4985 }
4986
4987 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4988 set_result(res);
4989 return true;
4990 }
4991
4992 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4993 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4994 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4995 RegionNode* region = new RegionNode(2);
4996 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4997
4998 if (type_array_guard) {
4999 generate_typeArray_guard(klass_node, region);
5000 if (region->req() == 3) {
5001 phi->add_req(klass_node);
5002 }
5003 }
5004 Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
5005 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
5006
5007 // Can be null if not initialized yet, just deopt
5008 Node* null_ctl = top();
5009 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
5010
5011 region->init_req(1, control());
5012 phi->init_req(1, refined_klass);
5013
5014 set_control(_gvn.transform(region));
5015 return _gvn.transform(phi);
5016 }
5017
5018 // Load the non-refined array klass from an ObjArrayKlass.
5019 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5020 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5021 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5022 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5023 }
5024
5025 RegionNode* region = new RegionNode(2);
5026 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5027
5028 generate_typeArray_guard(klass_node, region);
5029 if (region->req() == 3) {
5030 phi->add_req(klass_node);
5031 }
5032 Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
5033 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5034
5035 region->init_req(1, control());
5036 phi->init_req(1, super_klass);
5037
5038 set_control(_gvn.transform(region));
5039 return _gvn.transform(phi);
5040 }
5041
5042 //-----------------------inline_native_newArray--------------------------
5043 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5044 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5045 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5046 Node* mirror;
5047 Node* count_val;
5048 if (uninitialized) {
5049 null_check_receiver();
5050 mirror = argument(1);
5051 count_val = argument(2);
5052 } else {
5053 mirror = argument(0);
5054 count_val = argument(1);
5055 }
5056
5057 mirror = null_check(mirror);
5058 // If mirror or obj is dead, only null-path is taken.
5059 if (stopped()) return true;
5060
5061 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5062 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5063 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5081 CallJavaNode* slow_call = nullptr;
5082 if (uninitialized) {
5083 // Generate optimized virtual call (holder class 'Unsafe' is final)
5084 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5085 } else {
5086 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5087 }
5088 Node* slow_result = set_results_for_java_call(slow_call);
5089 // this->control() comes from set_results_for_java_call
5090 result_reg->set_req(_slow_path, control());
5091 result_val->set_req(_slow_path, slow_result);
5092 result_io ->set_req(_slow_path, i_o());
5093 result_mem->set_req(_slow_path, reset_memory());
5094 }
5095
5096 set_control(normal_ctl);
5097 if (!stopped()) {
5098 // Normal case: The array type has been cached in the java.lang.Class.
5099 // The following call works fine even if the array type is polymorphic.
5100 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5101
5102 klass_node = load_default_refined_array_klass(klass_node);
5103
5104 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
5105 result_reg->init_req(_normal_path, control());
5106 result_val->init_req(_normal_path, obj);
5107 result_io ->init_req(_normal_path, i_o());
5108 result_mem->init_req(_normal_path, reset_memory());
5109
5110 if (uninitialized) {
5111 // Mark the allocation so that zeroing is skipped
5112 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5113 alloc->maybe_set_complete(&_gvn);
5114 }
5115 }
5116
5117 // Return the combined state.
5118 set_i_o( _gvn.transform(result_io) );
5119 set_all_memory( _gvn.transform(result_mem));
5120
5121 C->set_has_split_ifs(true); // Has chance for split-if optimization
5122 set_result(result_reg, result_val);
5123 return true;
5172 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5173 { PreserveReexecuteState preexecs(this);
5174 jvms()->set_should_reexecute(true);
5175
5176 array_type_mirror = null_check(array_type_mirror);
5177 original = null_check(original);
5178
5179 // Check if a null path was taken unconditionally.
5180 if (stopped()) return true;
5181
5182 Node* orig_length = load_array_length(original);
5183
5184 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5185 klass_node = null_check(klass_node);
5186
5187 RegionNode* bailout = new RegionNode(1);
5188 record_for_igvn(bailout);
5189
5190 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5191 // Bail out if that is so.
5192 // Inline type array may have object field that would require a
5193 // write barrier. Conservatively, go to slow path.
5194 // TODO 8251971: Optimize for the case when flat src/dst are later found
5195 // to not contain oops (i.e., move this check to the macro expansion phase).
5196 // TODO 8382226: Revisit for flat abstract value class arrays
5197 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5198 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5199 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5200 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5201 // Can src array be flat and contain oops?
5202 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5203 // Can dest array be flat and contain oops?
5204 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5205 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5206
5207 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5208
5209 if (not_objArray != nullptr) {
5210 // Improve the klass node's type from the new optimistic assumption:
5211 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5212 bool not_flat = !UseArrayFlattening;
5213 bool not_null_free = !Arguments::is_valhalla_enabled();
5214 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5215 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5216 refined_klass_node = _gvn.transform(cast);
5217 }
5218
5219 // Bail out if either start or end is negative.
5220 generate_negative_guard(start, bailout, &start);
5221 generate_negative_guard(end, bailout, &end);
5222
5223 Node* length = end;
5224 if (_gvn.type(start) != TypeInt::ZERO) {
5225 length = _gvn.transform(new SubINode(end, start));
5226 }
5227
5228 // Bail out if length is negative (i.e., if start > end).
5229 // Without this the new_array would throw
5230 // NegativeArraySizeException but IllegalArgumentException is what
5231 // should be thrown
5232 generate_negative_guard(length, bailout, &length);
5233
5234 // Handle inline type arrays
5235 // TODO 8251971 This is too strong
5236 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5237 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5238 generate_fair_guard(null_free_array_test(original), bailout);
5239
5240 // Bail out if start is larger than the original length
5241 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5242 generate_negative_guard(orig_tail, bailout, &orig_tail);
5243
5244 if (bailout->req() > 1) {
5245 PreserveJVMState pjvms(this);
5246 set_control(_gvn.transform(bailout));
5247 uncommon_trap(Deoptimization::Reason_intrinsic,
5248 Deoptimization::Action_maybe_recompile);
5249 }
5250
5251 if (!stopped()) {
5252 // How many elements will we copy from the original?
5253 // The answer is MinI(orig_tail, length).
5254 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5255
5256 // Generate a direct call to the right arraycopy function(s).
5257 // We know the copy is disjoint but we might not know if the
5258 // oop stores need checking.
5259 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5279 }
5280 }
5281
5282 bool validated = false;
5283 // Reason_class_check rather than Reason_intrinsic because we
5284 // want to intrinsify even if this traps.
5285 if (!too_many_traps(Deoptimization::Reason_class_check)) {
5286 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5287
5288 if (not_subtype_ctrl != top()) {
5289 PreserveJVMState pjvms(this);
5290 set_control(not_subtype_ctrl);
5291 uncommon_trap(Deoptimization::Reason_class_check,
5292 Deoptimization::Action_make_not_entrant);
5293 assert(stopped(), "Should be stopped");
5294 }
5295 validated = true;
5296 }
5297
5298 if (!stopped()) {
5299 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5300
5301 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5302 load_object_klass(original), klass_node);
5303 if (!is_copyOfRange) {
5304 ac->set_copyof(validated);
5305 } else {
5306 ac->set_copyofrange(validated);
5307 }
5308 Node* n = _gvn.transform(ac);
5309 if (n == ac) {
5310 ac->connect_outputs(this);
5311 } else {
5312 assert(validated, "shouldn't transform if all arguments not validated");
5313 set_all_memory(n);
5314 }
5315 }
5316 }
5317 } // original reexecute is set back here
5318
5319 C->set_has_split_ifs(true); // Has chance for split-if optimization
5351
5352 //-----------------------generate_method_call----------------------------
5353 // Use generate_method_call to make a slow-call to the real
5354 // method if the fast path fails. An alternative would be to
5355 // use a stub like OptoRuntime::slow_arraycopy_Java.
5356 // This only works for expanding the current library call,
5357 // not another intrinsic. (E.g., don't use this for making an
5358 // arraycopy call inside of the copyOf intrinsic.)
5359 CallJavaNode*
5360 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5361 // When compiling the intrinsic method itself, do not use this technique.
5362 guarantee(callee() != C->method(), "cannot make slow-call to self");
5363
5364 ciMethod* method = callee();
5365 // ensure the JVMS we have will be correct for this call
5366 guarantee(method_id == method->intrinsic_id(), "must match");
5367
5368 const TypeFunc* tf = TypeFunc::make(method);
5369 if (res_not_null) {
5370 assert(tf->return_type() == T_OBJECT, "");
5371 const TypeTuple* range = tf->range_cc();
5372 const Type** fields = TypeTuple::fields(range->cnt());
5373 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5374 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5375 tf = TypeFunc::make(tf->domain_cc(), new_range);
5376 }
5377 CallJavaNode* slow_call;
5378 if (is_static) {
5379 assert(!is_virtual, "");
5380 slow_call = new CallStaticJavaNode(C, tf,
5381 SharedRuntime::get_resolve_static_call_stub(), method);
5382 } else if (is_virtual) {
5383 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5384 int vtable_index = Method::invalid_vtable_index;
5385 if (UseInlineCaches) {
5386 // Suppress the vtable call
5387 } else {
5388 // hashCode and clone are not a miranda methods,
5389 // so the vtable index is fixed.
5390 // No need to use the linkResolver to get it.
5391 vtable_index = method->vtable_index();
5392 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5393 "bad index %d", vtable_index);
5394 }
5395 slow_call = new CallDynamicJavaNode(tf,
5412 set_edges_for_java_call(slow_call);
5413 return slow_call;
5414 }
5415
5416
5417 /**
5418 * Build special case code for calls to hashCode on an object. This call may
5419 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5420 * slightly different code.
5421 */
5422 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5423 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5424 assert(!(is_virtual && is_static), "either virtual, special, or static");
5425
5426 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5427
5428 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5429 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5430 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5431 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5432 Node* obj = argument(0);
5433
5434 // Don't intrinsify hashcode on inline types for now.
5435 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5436 if (gvn().type(obj)->is_inlinetypeptr()) {
5437 return false;
5438 }
5439
5440 if (!is_static) {
5441 // Check for hashing null object
5442 obj = null_check_receiver();
5443 if (stopped()) return true; // unconditionally null
5444 result_reg->init_req(_null_path, top());
5445 result_val->init_req(_null_path, top());
5446 } else {
5447 // Do a null check, and return zero if null.
5448 // System.identityHashCode(null) == 0
5449 Node* null_ctl = top();
5450 obj = null_check_oop(obj, &null_ctl);
5451 result_reg->init_req(_null_path, null_ctl);
5452 result_val->init_req(_null_path, _gvn.intcon(0));
5453 }
5454
5455 // Unconditionally null? Then return right away.
5456 if (stopped()) {
5457 set_control( result_reg->in(_null_path));
5458 if (!stopped())
5459 set_result(result_val->in(_null_path));
5460 return true;
5461 }
5462
5463 // We only go to the fast case code if we pass a number of guards. The
5464 // paths which do not pass are accumulated in the slow_region.
5465 RegionNode* slow_region = new RegionNode(1);
5466 record_for_igvn(slow_region);
5467
5468 // If this is a virtual call, we generate a funny guard. We pull out
5469 // the vtable entry corresponding to hashCode() from the target object.
5470 // If the target method which we are calling happens to be the native
5471 // Object hashCode() method, we pass the guard. We do not need this
5472 // guard for non-virtual calls -- the caller is known to be the native
5473 // Object hashCode().
5474 if (is_virtual) {
5475 // After null check, get the object's klass.
5476 Node* obj_klass = load_object_klass(obj);
5477 generate_virtual_guard(obj_klass, slow_region);
5478 }
5479
5480 // Get the header out of the object, use LoadMarkNode when available
5481 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5482 // The control of the load must be null. Otherwise, the load can move before
5483 // the null check after castPP removal.
5484 Node* no_ctrl = nullptr;
5485 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5486
5487 if (!UseObjectMonitorTable) {
5488 // Test the header to see if it is safe to read w.r.t. locking.
5489 // We cannot use the inline type mask as this may check bits that are overridden
5490 // by an object monitor's pointer when inflating locking.
5491 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5492 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5493 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5494 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5495 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5496
5497 generate_slow_guard(test_monitor, slow_region);
5498 }
5499
5500 // Get the hash value and check to see that it has been properly assigned.
5501 // We depend on hash_mask being at most 32 bits and avoid the use of
5502 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5503 // vm: see markWord.hpp.
5504 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5505 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5506 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5507 // This hack lets the hash bits live anywhere in the mark object now, as long
5508 // as the shift drops the relevant bits into the low 32 bits. Note that
5509 // Java spec says that HashCode is an int so there's no point in capturing
5510 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5538 // this->control() comes from set_results_for_java_call
5539 result_reg->init_req(_slow_path, control());
5540 result_val->init_req(_slow_path, slow_result);
5541 result_io ->set_req(_slow_path, i_o());
5542 result_mem ->set_req(_slow_path, reset_memory());
5543 }
5544
5545 // Return the combined state.
5546 set_i_o( _gvn.transform(result_io) );
5547 set_all_memory( _gvn.transform(result_mem));
5548
5549 set_result(result_reg, result_val);
5550 return true;
5551 }
5552
5553 //---------------------------inline_native_getClass----------------------------
5554 // public final native Class<?> java.lang.Object.getClass();
5555 //
5556 // Build special case code for calls to getClass on an object.
5557 bool LibraryCallKit::inline_native_getClass() {
5558 Node* obj = argument(0);
5559 if (obj->is_InlineType()) {
5560 const Type* t = _gvn.type(obj);
5561 if (t->maybe_null()) {
5562 null_check(obj);
5563 }
5564 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5565 return true;
5566 }
5567 obj = null_check_receiver();
5568 if (stopped()) return true;
5569 set_result(load_mirror_from_klass(load_object_klass(obj)));
5570 return true;
5571 }
5572
5573 //-----------------inline_native_Reflection_getCallerClass---------------------
5574 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5575 //
5576 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5577 //
5578 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5579 // in that it must skip particular security frames and checks for
5580 // caller sensitive methods.
5581 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5582 #ifndef PRODUCT
5583 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5584 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5585 }
5586 #endif
5587
5969 // not cloneable or finalizer => slow path to out-of-line Object.clone
5970 //
5971 // The general case has two steps, allocation and copying.
5972 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5973 //
5974 // Copying also has two cases, oop arrays and everything else.
5975 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5976 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5977 //
5978 // These steps fold up nicely if and when the cloned object's klass
5979 // can be sharply typed as an object array, a type array, or an instance.
5980 //
5981 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5982 PhiNode* result_val;
5983
5984 // Set the reexecute bit for the interpreter to reexecute
5985 // the bytecode that invokes Object.clone if deoptimization happens.
5986 { PreserveReexecuteState preexecs(this);
5987 jvms()->set_should_reexecute(true);
5988
5989 Node* obj = argument(0);
5990 obj = null_check_receiver();
5991 if (stopped()) return true;
5992
5993 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5994 if (obj_type->is_inlinetypeptr()) {
5995 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5996 // no identity.
5997 set_result(obj);
5998 return true;
5999 }
6000
6001 // If we are going to clone an instance, we need its exact type to
6002 // know the number and types of fields to convert the clone to
6003 // loads/stores. Maybe a speculative type can help us.
6004 if (!obj_type->klass_is_exact() &&
6005 obj_type->speculative_type() != nullptr &&
6006 obj_type->speculative_type()->is_instance_klass() &&
6007 !obj_type->speculative_type()->is_inlinetype()) {
6008 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6009 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6010 !spec_ik->has_injected_fields()) {
6011 if (!obj_type->isa_instptr() ||
6012 obj_type->is_instptr()->instance_klass()->has_subklass()) {
6013 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6014 }
6015 }
6016 }
6017
6018 // Conservatively insert a memory barrier on all memory slices.
6019 // Do not let writes into the original float below the clone.
6020 insert_mem_bar(Op_MemBarCPUOrder);
6021
6022 // paths into result_reg:
6023 enum {
6024 _slow_path = 1, // out-of-line call to clone method (virtual or not)
6025 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
6026 _array_path, // plain array allocation, plus arrayof_long_arraycopy
6027 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
6028 PATH_LIMIT
6029 };
6030 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6031 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6032 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
6033 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6034 record_for_igvn(result_reg);
6035
6036 Node* obj_klass = load_object_klass(obj);
6037 // We only go to the fast case code if we pass a number of guards.
6038 // The paths which do not pass are accumulated in the slow_region.
6039 RegionNode* slow_region = new RegionNode(1);
6040 record_for_igvn(slow_region);
6041
6042 Node* array_obj = obj;
6043 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6044 if (array_ctl != nullptr) {
6045 // It's an array.
6046 PreserveJVMState pjvms(this);
6047 set_control(array_ctl);
6048
6049 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6050 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6051 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6052 obj_type->can_be_inline_array() &&
6053 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6054 // Flat inline type array may have object field that would require a
6055 // write barrier. Conservatively, go to slow path.
6056 generate_fair_guard(flat_array_test(obj_klass), slow_region);
6057 }
6058
6059 if (!stopped()) {
6060 Node* obj_length = load_array_length(array_obj);
6061 Node* array_size = nullptr; // Size of the array without object alignment padding.
6062 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6063
6064 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6065 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6066 // If it is an oop array, it requires very special treatment,
6067 // because gc barriers are required when accessing the array.
6068 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6069 if (is_obja != nullptr) {
6070 PreserveJVMState pjvms2(this);
6071 set_control(is_obja);
6072 // Generate a direct call to the right arraycopy function(s).
6073 // Clones are always tightly coupled.
6074 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6075 ac->set_clone_oop_array();
6076 Node* n = _gvn.transform(ac);
6077 assert(n == ac, "cannot disappear");
6078 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6079
6080 result_reg->init_req(_objArray_path, control());
6081 result_val->init_req(_objArray_path, alloc_obj);
6082 result_i_o ->set_req(_objArray_path, i_o());
6083 result_mem ->set_req(_objArray_path, reset_memory());
6084 }
6085 }
6086 // Otherwise, there are no barriers to worry about.
6087 // (We can dispense with card marks if we know the allocation
6088 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
6089 // causes the non-eden paths to take compensating steps to
6090 // simulate a fresh allocation, so that no further
6091 // card marks are required in compiled code to initialize
6092 // the object.)
6093
6094 if (!stopped()) {
6095 copy_to_clone(obj, alloc_obj, array_size, true);
6096
6097 // Present the results of the copy.
6098 result_reg->init_req(_array_path, control());
6099 result_val->init_req(_array_path, alloc_obj);
6100 result_i_o ->set_req(_array_path, i_o());
6101 result_mem ->set_req(_array_path, reset_memory());
6102 }
6103 }
6104 }
6105
6106 if (!stopped()) {
6107 // It's an instance (we did array above). Make the slow-path tests.
6108 // If this is a virtual call, we generate a funny guard. We grab
6109 // the vtable entry corresponding to clone() from the target object.
6110 // If the target method which we are calling happens to be the
6111 // Object clone() method, we pass the guard. We do not need this
6112 // guard for non-virtual calls; the caller is known to be the native
6113 // Object clone().
6114 if (is_virtual) {
6115 generate_virtual_guard(obj_klass, slow_region);
6116 }
6117
6118 // The object must be easily cloneable and must not have a finalizer.
6119 // Both of these conditions may be checked in a single test.
6120 // We could optimize the test further, but we don't care.
6121 generate_misc_flags_guard(obj_klass,
6122 // Test both conditions:
6123 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6124 // Must be cloneable but not finalizer:
6125 KlassFlags::_misc_is_cloneable_fast,
6217 set_jvms(sfpt->jvms());
6218 _reexecute_sp = jvms()->sp();
6219
6220 return saved_jvms;
6221 }
6222 }
6223 }
6224 return nullptr;
6225 }
6226
6227 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6228 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6229 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6230 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6231 uint size = alloc->req();
6232 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6233 old_jvms->set_map(sfpt);
6234 for (uint i = 0; i < size; i++) {
6235 sfpt->init_req(i, alloc->in(i));
6236 }
6237 int adjustment = 1;
6238 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6239 if (ary_klass_ptr->is_null_free()) {
6240 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6241 // also requires the componentType and initVal on stack for re-execution.
6242 // Re-create and push the componentType.
6243 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6244 ciInstance* instance = klass->component_mirror_instance();
6245 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6246 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6247 adjustment++;
6248 }
6249 // re-push array length for deoptimization
6250 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6251 if (ary_klass_ptr->is_null_free()) {
6252 // Re-create and push the initVal.
6253 Node* init_val = alloc->in(AllocateNode::InitValue);
6254 if (init_val == nullptr) {
6255 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6256 } else if (UseCompressedOops) {
6257 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6258 }
6259 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6260 adjustment++;
6261 }
6262 old_jvms->set_sp(old_jvms->sp() + adjustment);
6263 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6264 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6265 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6266 old_jvms->set_should_reexecute(true);
6267
6268 sfpt->set_i_o(map()->i_o());
6269 sfpt->set_memory(map()->memory());
6270 sfpt->set_control(map()->control());
6271 return sfpt;
6272 }
6273
6274 // In case of a deoptimization, we restart execution at the
6275 // allocation, allocating a new array. We would leave an uninitialized
6276 // array in the heap that GCs wouldn't expect. Move the allocation
6277 // after the traps so we don't allocate the array if we
6278 // deoptimize. This is possible because tightly_coupled_allocation()
6279 // guarantees there's no observer of the allocated array at this point
6280 // and the control flow is simple enough.
6281 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6282 int saved_reexecute_sp, uint new_idx) {
6283 if (saved_jvms_before_guards != nullptr && !stopped()) {
6284 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6285
6286 assert(alloc != nullptr, "only with a tightly coupled allocation");
6287 // restore JVM state to the state at the arraycopy
6288 saved_jvms_before_guards->map()->set_control(map()->control());
6289 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6290 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6291 // If we've improved the types of some nodes (null check) while
6292 // emitting the guards, propagate them to the current state
6293 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6294 set_jvms(saved_jvms_before_guards);
6295 _reexecute_sp = saved_reexecute_sp;
6296
6297 // Remove the allocation from above the guards
6298 CallProjections* callprojs = alloc->extract_projections(true);
6299 InitializeNode* init = alloc->initialization();
6300 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6301 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6302 init->replace_mem_projs_by(alloc_mem, C);
6303
6304 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6305 // the allocation (i.e. is only valid if the allocation succeeds):
6306 // 1) replace CastIINode with AllocateArrayNode's length here
6307 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6308 //
6309 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6310 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6311 Node* init_control = init->proj_out(TypeFunc::Control);
6312 Node* alloc_length = alloc->Ideal_length();
6313 #ifdef ASSERT
6314 Node* prev_cast = nullptr;
6315 #endif
6316 for (uint i = 0; i < init_control->outcnt(); i++) {
6317 Node* init_out = init_control->raw_out(i);
6318 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6319 #ifdef ASSERT
6320 if (prev_cast == nullptr) {
6321 prev_cast = init_out;
6323 if (prev_cast->cmp(*init_out) == false) {
6324 prev_cast->dump();
6325 init_out->dump();
6326 assert(false, "not equal CastIINode");
6327 }
6328 }
6329 #endif
6330 C->gvn_replace_by(init_out, alloc_length);
6331 }
6332 }
6333 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6334
6335 // move the allocation here (after the guards)
6336 _gvn.hash_delete(alloc);
6337 alloc->set_req(TypeFunc::Control, control());
6338 alloc->set_req(TypeFunc::I_O, i_o());
6339 Node *mem = reset_memory();
6340 set_all_memory(mem);
6341 alloc->set_req(TypeFunc::Memory, mem);
6342 set_control(init->proj_out_or_null(TypeFunc::Control));
6343 set_i_o(callprojs->fallthrough_ioproj);
6344
6345 // Update memory as done in GraphKit::set_output_for_allocation()
6346 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6347 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6348 if (ary_type->isa_aryptr() && length_type != nullptr) {
6349 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6350 }
6351 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6352 int elemidx = C->get_alias_index(telemref);
6353 // Need to properly move every memory projection for the Initialize
6354 #ifdef ASSERT
6355 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6356 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6357 #endif
6358 auto move_proj = [&](ProjNode* proj) {
6359 int alias_idx = C->get_alias_index(proj->adr_type());
6360 assert(alias_idx == Compile::AliasIdxRaw ||
6361 alias_idx == elemidx ||
6362 alias_idx == mark_idx ||
6363 alias_idx == klass_idx, "should be raw memory or array element type");
6673 top_src = src_type->isa_aryptr();
6674 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6675 src_spec = true;
6676 }
6677 if (!has_dest) {
6678 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6679 dest_type = _gvn.type(dest);
6680 top_dest = dest_type->isa_aryptr();
6681 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6682 dest_spec = true;
6683 }
6684 }
6685 }
6686
6687 if (has_src && has_dest && can_emit_guards) {
6688 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6689 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6690 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6691 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6692
6693 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6694 // If both arrays are object arrays then having the exact types
6695 // for both will remove the need for a subtype check at runtime
6696 // before the call and may make it possible to pick a faster copy
6697 // routine (without a subtype check on every element)
6698 // Do we have the exact type of src?
6699 bool could_have_src = src_spec;
6700 // Do we have the exact type of dest?
6701 bool could_have_dest = dest_spec;
6702 ciKlass* src_k = nullptr;
6703 ciKlass* dest_k = nullptr;
6704 if (!src_spec) {
6705 src_k = src_type->speculative_type_not_null();
6706 if (src_k != nullptr && src_k->is_array_klass()) {
6707 could_have_src = true;
6708 }
6709 }
6710 if (!dest_spec) {
6711 dest_k = dest_type->speculative_type_not_null();
6712 if (dest_k != nullptr && dest_k->is_array_klass()) {
6713 could_have_dest = true;
6714 }
6715 }
6716 if (could_have_src && could_have_dest) {
6717 // If we can have both exact types, emit the missing guards
6718 if (could_have_src && !src_spec) {
6719 src = maybe_cast_profiled_obj(src, src_k, true);
6720 src_type = _gvn.type(src);
6721 top_src = src_type->isa_aryptr();
6722 }
6723 if (could_have_dest && !dest_spec) {
6724 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6725 dest_type = _gvn.type(dest);
6726 top_dest = dest_type->isa_aryptr();
6727 }
6728 }
6729 }
6730 }
6731
6732 ciMethod* trap_method = method();
6733 int trap_bci = bci();
6734 if (saved_jvms_before_guards != nullptr) {
6735 trap_method = alloc->jvms()->method();
6736 trap_bci = alloc->jvms()->bci();
6737 }
6738
6739 bool negative_length_guard_generated = false;
6740
6741 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6742 can_emit_guards && !src->is_top() && !dest->is_top()) {
6743 // validate arguments: enables transformation the ArrayCopyNode
6744 validated = true;
6745
6746 RegionNode* slow_region = new RegionNode(1);
6747 record_for_igvn(slow_region);
6748
6749 // (1) src and dest are arrays.
6750 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6751 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6752
6753 // (2) src and dest arrays must have elements of the same BasicType
6754 // done at macro expansion or at Ideal transformation time
6755
6756 // (4) src_offset must not be negative.
6757 generate_negative_guard(src_offset, slow_region);
6758
6759 // (5) dest_offset must not be negative.
6760 generate_negative_guard(dest_offset, slow_region);
6761
6762 // (7) src_offset + length must not exceed length of src.
6763 generate_limit_guard(src_offset, length,
6764 load_array_length(src),
6765 slow_region);
6766
6767 // (8) dest_offset + length must not exceed length of dest.
6768 generate_limit_guard(dest_offset, length,
6769 load_array_length(dest),
6770 slow_region);
6771
6772 // (6) length must not be negative.
6773 // This is also checked in generate_arraycopy() during macro expansion, but
6774 // we also have to check it here for the case where the ArrayCopyNode will
6775 // be eliminated by Escape Analysis.
6776 if (EliminateAllocations) {
6777 generate_negative_guard(length, slow_region);
6778 negative_length_guard_generated = true;
6779 }
6780
6781 // (9) each element of an oop array must be assignable
6782 Node* dest_klass = load_object_klass(dest);
6783 Node* refined_dest_klass = dest_klass;
6784 if (src != dest) {
6785 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6786 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6787 slow_region->add_req(not_subtype_ctrl);
6788 }
6789
6790 // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6791 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6792 Node* src_klass = load_object_klass(src);
6793 Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6794 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6795 _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6796 MemNode::unordered));
6797 Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6798 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6799 _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6800 MemNode::unordered));
6801
6802 const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6803 jint props_value = (jint)props_null_restricted.value();
6804
6805 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6806 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6807 prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6808
6809 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6810 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6811 generate_fair_guard(tst, slow_region);
6812
6813 // TODO 8251971 This is too strong
6814 generate_fair_guard(flat_array_test(src), slow_region);
6815 generate_fair_guard(flat_array_test(dest), slow_region);
6816
6817 {
6818 PreserveJVMState pjvms(this);
6819 set_control(_gvn.transform(slow_region));
6820 uncommon_trap(Deoptimization::Reason_intrinsic,
6821 Deoptimization::Action_make_not_entrant);
6822 assert(stopped(), "Should be stopped");
6823 }
6824
6825 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6826 if (dest_klass_t == nullptr) {
6827 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6828 // are in a dead path.
6829 uncommon_trap(Deoptimization::Reason_intrinsic,
6830 Deoptimization::Action_make_not_entrant);
6831 return true;
6832 }
6833
6834 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6835 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6836 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6837 }
6838
6839 if (stopped()) {
6840 return true;
6841 }
6842
6843 Node* dest_klass = load_object_klass(dest);
6844 dest_klass = load_non_refined_array_klass(dest_klass);
6845
6846 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6847 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6848 // so the compiler has a chance to eliminate them: during macro expansion,
6849 // we have to set their control (CastPP nodes are eliminated).
6850 load_object_klass(src), dest_klass,
6851 load_array_length(src), load_array_length(dest));
6852
6853 ac->set_arraycopy(validated);
6854
6855 Node* n = _gvn.transform(ac);
6856 if (n == ac) {
6857 ac->connect_outputs(this);
6858 } else {
6859 assert(validated, "shouldn't transform if all arguments not validated");
6860 set_all_memory(n);
6861 }
6862 clear_upper_avx();
6863
6864
6865 return true;
6866 }
6867
6868
6869 // Helper function which determines if an arraycopy immediately follows
6870 // an allocation, with no intervening tests or other escapes for the object.
|