1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "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/jniHandles.inline.hpp"
68 #include "runtime/objectMonitor.hpp"
69 #include "runtime/sharedRuntime.hpp"
70 #include "runtime/stubRoutines.hpp"
71 #include "utilities/globalDefinitions.hpp"
72 #include "utilities/macros.hpp"
73 #include "utilities/powerOfTwo.hpp"
74
75 //---------------------------make_vm_intrinsic----------------------------
76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
77 vmIntrinsicID id = m->intrinsic_id();
78 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
79
80 if (!m->is_loaded()) {
81 // Do not attempt to inline unloaded methods.
82 return nullptr;
83 }
84
85 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
86 bool is_available = false;
87
88 {
89 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
90 // the compiler must transition to '_thread_in_vm' state because both
91 // methods access VM-internal data.
92 VM_ENTRY_MARK;
93 methodHandle mh(THREAD, m->get_Method());
94 is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
95 if (is_available && is_virtual) {
96 is_available = vmIntrinsics::does_virtual_dispatch(id);
97 }
98 }
99
100 if (is_available) {
101 assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
102 assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
103 return new LibraryIntrinsic(m, is_virtual,
104 vmIntrinsics::predicates_needed(id),
105 vmIntrinsics::does_virtual_dispatch(id),
106 id);
107 } else {
108 return nullptr;
109 }
110 }
111
112 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
113 LibraryCallKit kit(jvms, this);
114 Compile* C = kit.C;
115 int nodes = C->unique();
116 #ifndef PRODUCT
117 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
118 char buf[1000];
119 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
120 tty->print_cr("Intrinsic %s", str);
121 }
122 #endif
123 ciMethod* callee = kit.callee();
124 const int bci = kit.bci();
125 #ifdef ASSERT
126 Node* ctrl = kit.control();
127 #endif
128 // Try to inline the intrinsic.
129 if (callee->check_intrinsic_candidate() &&
130 kit.try_to_inline(_last_predicate)) {
131 const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
132 : "(intrinsic)";
133 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
134 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
135 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
136 if (C->log()) {
137 C->log()->elem("intrinsic id='%s'%s nodes='%d'",
138 vmIntrinsics::name_at(intrinsic_id()),
139 (is_virtual() ? " virtual='1'" : ""),
140 C->unique() - nodes);
141 }
142 // Push the result from the inlined method onto the stack.
143 kit.push_result();
144 return kit.transfer_exceptions_into_jvms();
145 }
146
147 // The intrinsic bailed out
148 assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
149 assert(jvms->map() == kit.map(), "Out of sync JVM state");
150 if (jvms->has_method()) {
151 // Not a root compile.
152 const char* msg;
153 if (callee->intrinsic_candidate()) {
154 msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
155 } else {
156 msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
157 : "failed to inline (intrinsic), method not annotated";
158 }
159 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
160 C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
161 } else {
162 // Root compile
163 ResourceMark rm;
164 stringStream msg_stream;
165 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
166 vmIntrinsics::name_at(intrinsic_id()),
167 is_virtual() ? " (virtual)" : "", bci);
168 const char *msg = msg_stream.freeze();
169 log_debug(jit, inlining)("%s", msg);
170 if (C->print_intrinsics() || C->print_inlining()) {
171 tty->print("%s", msg);
172 }
173 }
174 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
175
176 return nullptr;
177 }
178
179 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
180 LibraryCallKit kit(jvms, this);
181 Compile* C = kit.C;
182 int nodes = C->unique();
183 _last_predicate = predicate;
184 #ifndef PRODUCT
185 assert(is_predicated() && predicate < predicates_count(), "sanity");
186 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
187 char buf[1000];
188 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
189 tty->print_cr("Predicate for intrinsic %s", str);
190 }
191 #endif
192 ciMethod* callee = kit.callee();
193 const int bci = kit.bci();
194
195 Node* slow_ctl = kit.try_to_predicate(predicate);
196 if (!kit.failing()) {
197 const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
198 : "(intrinsic, predicate)";
199 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
200 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
201
202 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
203 if (C->log()) {
204 C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
205 vmIntrinsics::name_at(intrinsic_id()),
206 (is_virtual() ? " virtual='1'" : ""),
207 C->unique() - nodes);
208 }
209 return slow_ctl; // Could be null if the check folds.
210 }
211
212 // The intrinsic bailed out
213 if (jvms->has_method()) {
214 // Not a root compile.
215 const char* msg = "failed to generate predicate for intrinsic";
216 CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
217 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
218 } else {
219 // Root compile
220 ResourceMark rm;
221 stringStream msg_stream;
222 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
223 vmIntrinsics::name_at(intrinsic_id()),
224 is_virtual() ? " (virtual)" : "", bci);
225 const char *msg = msg_stream.freeze();
226 log_debug(jit, inlining)("%s", msg);
227 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
228 }
229 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
230 return nullptr;
231 }
232
233 bool LibraryCallKit::try_to_inline(int predicate) {
234 // Handle symbolic names for otherwise undistinguished boolean switches:
235 const bool is_store = true;
236 const bool is_compress = true;
237 const bool is_static = true;
238 const bool is_volatile = true;
239
240 if (!jvms()->has_method()) {
241 // Root JVMState has a null method.
242 assert(map()->memory()->Opcode() == Op_Parm, "");
243 // Insert the memory aliasing node
244 set_all_memory(reset_memory());
245 }
246 assert(merged_memory(), "");
247
248 switch (intrinsic_id()) {
249 case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
250 case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);
251 case vmIntrinsics::_getClass: return inline_native_getClass();
252
253 case vmIntrinsics::_ceil:
254 case vmIntrinsics::_floor:
255 case vmIntrinsics::_rint:
256 case vmIntrinsics::_dsin:
257 case vmIntrinsics::_dcos:
258 case vmIntrinsics::_dtan:
259 case vmIntrinsics::_dsinh:
260 case vmIntrinsics::_dtanh:
261 case vmIntrinsics::_dcbrt:
262 case vmIntrinsics::_dabs:
263 case vmIntrinsics::_fabs:
264 case vmIntrinsics::_iabs:
265 case vmIntrinsics::_labs:
266 case vmIntrinsics::_datan2:
267 case vmIntrinsics::_dsqrt:
268 case vmIntrinsics::_dsqrt_strict:
269 case vmIntrinsics::_dexp:
270 case vmIntrinsics::_dlog:
271 case vmIntrinsics::_dlog10:
272 case vmIntrinsics::_dpow:
273 case vmIntrinsics::_dcopySign:
274 case vmIntrinsics::_fcopySign:
275 case vmIntrinsics::_dsignum:
276 case vmIntrinsics::_roundF:
277 case vmIntrinsics::_roundD:
278 case vmIntrinsics::_fsignum: return inline_math_native(intrinsic_id());
279
280 case vmIntrinsics::_notify:
281 case vmIntrinsics::_notifyAll:
282 return inline_notify(intrinsic_id());
283
284 case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);
285 case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);
286 case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);
287 case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);
288 case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);
289 case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);
290 case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();
291 case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();
292 case vmIntrinsics::_multiplyHigh: return inline_math_multiplyHigh();
293 case vmIntrinsics::_unsignedMultiplyHigh: return inline_math_unsignedMultiplyHigh();
294 case vmIntrinsics::_negateExactI: return inline_math_negateExactI();
295 case vmIntrinsics::_negateExactL: return inline_math_negateExactL();
296 case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);
297 case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);
298
299 case vmIntrinsics::_arraycopy: return inline_arraycopy();
300
301 case vmIntrinsics::_arraySort: return inline_array_sort();
302 case vmIntrinsics::_arrayPartition: return inline_array_partition();
303
304 case vmIntrinsics::_compareToL: return inline_string_compareTo(StrIntrinsicNode::LL);
305 case vmIntrinsics::_compareToU: return inline_string_compareTo(StrIntrinsicNode::UU);
306 case vmIntrinsics::_compareToLU: return inline_string_compareTo(StrIntrinsicNode::LU);
307 case vmIntrinsics::_compareToUL: return inline_string_compareTo(StrIntrinsicNode::UL);
308
309 case vmIntrinsics::_indexOfL: return inline_string_indexOf(StrIntrinsicNode::LL);
310 case vmIntrinsics::_indexOfU: return inline_string_indexOf(StrIntrinsicNode::UU);
311 case vmIntrinsics::_indexOfUL: return inline_string_indexOf(StrIntrinsicNode::UL);
312 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
313 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
314 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
315 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
316 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
317
318 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
319
320 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
321
322 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
323 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
324 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
325 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
326
327 case vmIntrinsics::_compressStringC:
328 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
329 case vmIntrinsics::_inflateStringC:
330 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
331
332 case vmIntrinsics::_makePrivateBuffer: return inline_unsafe_make_private_buffer();
333 case vmIntrinsics::_finishPrivateBuffer: return inline_unsafe_finish_private_buffer();
334 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
335 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
336 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
337 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
338 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
339 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
340 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
341 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
342 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
343 case vmIntrinsics::_getValue: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false, true);
344
345 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
346 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
347 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
348 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
349 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
350 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
351 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
352 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
353 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
354 case vmIntrinsics::_putValue: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false, true);
355
356 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
357 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
358 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
359 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
360 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
361 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
362 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
363 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
364 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
365
366 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
367 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
368 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
369 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
370 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
371 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
372 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
373 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
374 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
375
376 case vmIntrinsics::_getShortUnaligned: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, true);
377 case vmIntrinsics::_getCharUnaligned: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, true);
378 case vmIntrinsics::_getIntUnaligned: return inline_unsafe_access(!is_store, T_INT, Relaxed, true);
379 case vmIntrinsics::_getLongUnaligned: return inline_unsafe_access(!is_store, T_LONG, Relaxed, true);
380
381 case vmIntrinsics::_putShortUnaligned: return inline_unsafe_access( is_store, T_SHORT, Relaxed, true);
382 case vmIntrinsics::_putCharUnaligned: return inline_unsafe_access( is_store, T_CHAR, Relaxed, true);
383 case vmIntrinsics::_putIntUnaligned: return inline_unsafe_access( is_store, T_INT, Relaxed, true);
384 case vmIntrinsics::_putLongUnaligned: return inline_unsafe_access( is_store, T_LONG, Relaxed, true);
385
386 case vmIntrinsics::_getReferenceAcquire: return inline_unsafe_access(!is_store, T_OBJECT, Acquire, false);
387 case vmIntrinsics::_getBooleanAcquire: return inline_unsafe_access(!is_store, T_BOOLEAN, Acquire, false);
388 case vmIntrinsics::_getByteAcquire: return inline_unsafe_access(!is_store, T_BYTE, Acquire, false);
389 case vmIntrinsics::_getShortAcquire: return inline_unsafe_access(!is_store, T_SHORT, Acquire, false);
390 case vmIntrinsics::_getCharAcquire: return inline_unsafe_access(!is_store, T_CHAR, Acquire, false);
391 case vmIntrinsics::_getIntAcquire: return inline_unsafe_access(!is_store, T_INT, Acquire, false);
392 case vmIntrinsics::_getLongAcquire: return inline_unsafe_access(!is_store, T_LONG, Acquire, false);
393 case vmIntrinsics::_getFloatAcquire: return inline_unsafe_access(!is_store, T_FLOAT, Acquire, false);
394 case vmIntrinsics::_getDoubleAcquire: return inline_unsafe_access(!is_store, T_DOUBLE, Acquire, false);
395
396 case vmIntrinsics::_putReferenceRelease: return inline_unsafe_access( is_store, T_OBJECT, Release, false);
397 case vmIntrinsics::_putBooleanRelease: return inline_unsafe_access( is_store, T_BOOLEAN, Release, false);
398 case vmIntrinsics::_putByteRelease: return inline_unsafe_access( is_store, T_BYTE, Release, false);
399 case vmIntrinsics::_putShortRelease: return inline_unsafe_access( is_store, T_SHORT, Release, false);
400 case vmIntrinsics::_putCharRelease: return inline_unsafe_access( is_store, T_CHAR, Release, false);
401 case vmIntrinsics::_putIntRelease: return inline_unsafe_access( is_store, T_INT, Release, false);
402 case vmIntrinsics::_putLongRelease: return inline_unsafe_access( is_store, T_LONG, Release, false);
403 case vmIntrinsics::_putFloatRelease: return inline_unsafe_access( is_store, T_FLOAT, Release, false);
404 case vmIntrinsics::_putDoubleRelease: return inline_unsafe_access( is_store, T_DOUBLE, Release, false);
405
406 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
407 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
408 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
409 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
410 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
411 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
412 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
413 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
414 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
415
416 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
417 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
418 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
419 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
420 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
421 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
422 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
423 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
424 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
425
426 case vmIntrinsics::_getFlatValue: return inline_unsafe_flat_access(!is_store, Relaxed);
427 case vmIntrinsics::_putFlatValue: return inline_unsafe_flat_access( is_store, Relaxed);
428
429 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
430 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
431 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
432 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
433 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
434
435 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
436 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
437 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
438 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
439 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
440 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
441 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
442 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
443 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
444 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
445 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
446 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
447 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
448 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
449 case vmIntrinsics::_weakCompareAndSetIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Release);
450 case vmIntrinsics::_weakCompareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Volatile);
451 case vmIntrinsics::_weakCompareAndSetLongPlain: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Relaxed);
452 case vmIntrinsics::_weakCompareAndSetLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Acquire);
453 case vmIntrinsics::_weakCompareAndSetLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Release);
454 case vmIntrinsics::_weakCompareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Volatile);
455
456 case vmIntrinsics::_compareAndExchangeReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Volatile);
457 case vmIntrinsics::_compareAndExchangeReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Acquire);
458 case vmIntrinsics::_compareAndExchangeReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Release);
459 case vmIntrinsics::_compareAndExchangeByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Volatile);
460 case vmIntrinsics::_compareAndExchangeByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Acquire);
461 case vmIntrinsics::_compareAndExchangeByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Release);
462 case vmIntrinsics::_compareAndExchangeShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Volatile);
463 case vmIntrinsics::_compareAndExchangeShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Acquire);
464 case vmIntrinsics::_compareAndExchangeShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Release);
465 case vmIntrinsics::_compareAndExchangeInt: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Volatile);
466 case vmIntrinsics::_compareAndExchangeIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Acquire);
467 case vmIntrinsics::_compareAndExchangeIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Release);
468 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
469 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
470 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
471
472 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
473 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
474 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
475 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
476
477 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
478 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
479 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
480 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
481 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
482
483 case vmIntrinsics::_loadFence:
484 case vmIntrinsics::_storeFence:
485 case vmIntrinsics::_storeStoreFence:
486 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
487
488 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
489
490 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
491 case vmIntrinsics::_currentThread: return inline_native_currentThread();
492 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
493
494 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
495 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
496
497 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
498 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
499
500 #if INCLUDE_JVMTI
501 case vmIntrinsics::_notifyJvmtiVThreadStart: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
502 "notifyJvmtiStart", true, false);
503 case vmIntrinsics::_notifyJvmtiVThreadEnd: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
504 "notifyJvmtiEnd", false, true);
505 case vmIntrinsics::_notifyJvmtiVThreadMount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
506 "notifyJvmtiMount", false, false);
507 case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
508 "notifyJvmtiUnmount", false, false);
509 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
510 #endif
511
512 #ifdef JFR_HAVE_INTRINSICS
513 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
514 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
515 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
516 #endif
517 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
518 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
519 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
520 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
521 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
522 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
523 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
524 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
525 case vmIntrinsics::_getLength: return inline_native_getLength();
526 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
527 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
528 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
529 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
530 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
531 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
532 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
533
534 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
535 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
536 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
537 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
538 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
539 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
540 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
541 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
542
543 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
544
545 case vmIntrinsics::_isInstance:
546 case vmIntrinsics::_isHidden:
547 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
548
549 case vmIntrinsics::_floatToRawIntBits:
550 case vmIntrinsics::_floatToIntBits:
551 case vmIntrinsics::_intBitsToFloat:
552 case vmIntrinsics::_doubleToRawLongBits:
553 case vmIntrinsics::_doubleToLongBits:
554 case vmIntrinsics::_longBitsToDouble:
555 case vmIntrinsics::_floatToFloat16:
556 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
557 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
558 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
559 case vmIntrinsics::_floatIsFinite:
560 case vmIntrinsics::_floatIsInfinite:
561 case vmIntrinsics::_doubleIsFinite:
562 case vmIntrinsics::_doubleIsInfinite: return inline_fp_range_check(intrinsic_id());
563
564 case vmIntrinsics::_numberOfLeadingZeros_i:
565 case vmIntrinsics::_numberOfLeadingZeros_l:
566 case vmIntrinsics::_numberOfTrailingZeros_i:
567 case vmIntrinsics::_numberOfTrailingZeros_l:
568 case vmIntrinsics::_bitCount_i:
569 case vmIntrinsics::_bitCount_l:
570 case vmIntrinsics::_reverse_i:
571 case vmIntrinsics::_reverse_l:
572 case vmIntrinsics::_reverseBytes_i:
573 case vmIntrinsics::_reverseBytes_l:
574 case vmIntrinsics::_reverseBytes_s:
575 case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());
576
577 case vmIntrinsics::_compress_i:
578 case vmIntrinsics::_compress_l:
579 case vmIntrinsics::_expand_i:
580 case vmIntrinsics::_expand_l: return inline_bitshuffle_methods(intrinsic_id());
581
582 case vmIntrinsics::_compareUnsigned_i:
583 case vmIntrinsics::_compareUnsigned_l: return inline_compare_unsigned(intrinsic_id());
584
585 case vmIntrinsics::_divideUnsigned_i:
586 case vmIntrinsics::_divideUnsigned_l:
587 case vmIntrinsics::_remainderUnsigned_i:
588 case vmIntrinsics::_remainderUnsigned_l: return inline_divmod_methods(intrinsic_id());
589
590 case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();
591
592 case vmIntrinsics::_Reference_get0: return inline_reference_get0();
593 case vmIntrinsics::_Reference_refersTo0: return inline_reference_refersTo0(false);
594 case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
595 case vmIntrinsics::_Reference_clear0: return inline_reference_clear0(false);
596 case vmIntrinsics::_PhantomReference_clear0: return inline_reference_clear0(true);
597
598 case vmIntrinsics::_Class_cast: return inline_Class_cast();
599
600 case vmIntrinsics::_aescrypt_encryptBlock:
601 case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());
602
603 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
604 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
605 return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
606
607 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
608 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
609 return inline_electronicCodeBook_AESCrypt(intrinsic_id());
610
611 case vmIntrinsics::_counterMode_AESCrypt:
612 return inline_counterMode_AESCrypt(intrinsic_id());
613
614 case vmIntrinsics::_galoisCounterMode_AESCrypt:
615 return inline_galoisCounterMode_AESCrypt();
616
617 case vmIntrinsics::_md5_implCompress:
618 case vmIntrinsics::_sha_implCompress:
619 case vmIntrinsics::_sha2_implCompress:
620 case vmIntrinsics::_sha5_implCompress:
621 case vmIntrinsics::_sha3_implCompress:
622 return inline_digestBase_implCompress(intrinsic_id());
623 case vmIntrinsics::_double_keccak:
624 return inline_double_keccak();
625
626 case vmIntrinsics::_digestBase_implCompressMB:
627 return inline_digestBase_implCompressMB(predicate);
628
629 case vmIntrinsics::_multiplyToLen:
630 return inline_multiplyToLen();
631
632 case vmIntrinsics::_squareToLen:
633 return inline_squareToLen();
634
635 case vmIntrinsics::_mulAdd:
636 return inline_mulAdd();
637
638 case vmIntrinsics::_montgomeryMultiply:
639 return inline_montgomeryMultiply();
640 case vmIntrinsics::_montgomerySquare:
641 return inline_montgomerySquare();
642
643 case vmIntrinsics::_bigIntegerRightShiftWorker:
644 return inline_bigIntegerShift(true);
645 case vmIntrinsics::_bigIntegerLeftShiftWorker:
646 return inline_bigIntegerShift(false);
647
648 case vmIntrinsics::_vectorizedMismatch:
649 return inline_vectorizedMismatch();
650
651 case vmIntrinsics::_ghash_processBlocks:
652 return inline_ghash_processBlocks();
653 case vmIntrinsics::_chacha20Block:
654 return inline_chacha20Block();
655 case vmIntrinsics::_kyberNtt:
656 return inline_kyberNtt();
657 case vmIntrinsics::_kyberInverseNtt:
658 return inline_kyberInverseNtt();
659 case vmIntrinsics::_kyberNttMult:
660 return inline_kyberNttMult();
661 case vmIntrinsics::_kyberAddPoly_2:
662 return inline_kyberAddPoly_2();
663 case vmIntrinsics::_kyberAddPoly_3:
664 return inline_kyberAddPoly_3();
665 case vmIntrinsics::_kyber12To16:
666 return inline_kyber12To16();
667 case vmIntrinsics::_kyberBarrettReduce:
668 return inline_kyberBarrettReduce();
669 case vmIntrinsics::_dilithiumAlmostNtt:
670 return inline_dilithiumAlmostNtt();
671 case vmIntrinsics::_dilithiumAlmostInverseNtt:
672 return inline_dilithiumAlmostInverseNtt();
673 case vmIntrinsics::_dilithiumNttMult:
674 return inline_dilithiumNttMult();
675 case vmIntrinsics::_dilithiumMontMulByConstant:
676 return inline_dilithiumMontMulByConstant();
677 case vmIntrinsics::_dilithiumDecomposePoly:
678 return inline_dilithiumDecomposePoly();
679 case vmIntrinsics::_base64_encodeBlock:
680 return inline_base64_encodeBlock();
681 case vmIntrinsics::_base64_decodeBlock:
682 return inline_base64_decodeBlock();
683 case vmIntrinsics::_poly1305_processBlocks:
684 return inline_poly1305_processBlocks();
685 case vmIntrinsics::_intpoly_montgomeryMult_P256:
686 return inline_intpoly_montgomeryMult_P256();
687 case vmIntrinsics::_intpoly_assign:
688 return inline_intpoly_assign();
689 case vmIntrinsics::_encodeISOArray:
690 case vmIntrinsics::_encodeByteISOArray:
691 return inline_encodeISOArray(false);
692 case vmIntrinsics::_encodeAsciiArray:
693 return inline_encodeISOArray(true);
694
695 case vmIntrinsics::_updateCRC32:
696 return inline_updateCRC32();
697 case vmIntrinsics::_updateBytesCRC32:
698 return inline_updateBytesCRC32();
699 case vmIntrinsics::_updateByteBufferCRC32:
700 return inline_updateByteBufferCRC32();
701
702 case vmIntrinsics::_updateBytesCRC32C:
703 return inline_updateBytesCRC32C();
704 case vmIntrinsics::_updateDirectByteBufferCRC32C:
705 return inline_updateDirectByteBufferCRC32C();
706
707 case vmIntrinsics::_updateBytesAdler32:
708 return inline_updateBytesAdler32();
709 case vmIntrinsics::_updateByteBufferAdler32:
710 return inline_updateByteBufferAdler32();
711
712 case vmIntrinsics::_profileBoolean:
713 return inline_profileBoolean();
714 case vmIntrinsics::_isCompileConstant:
715 return inline_isCompileConstant();
716
717 case vmIntrinsics::_countPositives:
718 return inline_countPositives();
719
720 case vmIntrinsics::_fmaD:
721 case vmIntrinsics::_fmaF:
722 return inline_fma(intrinsic_id());
723
724 case vmIntrinsics::_isDigit:
725 case vmIntrinsics::_isLowerCase:
726 case vmIntrinsics::_isUpperCase:
727 case vmIntrinsics::_isWhitespace:
728 return inline_character_compare(intrinsic_id());
729
730 case vmIntrinsics::_min:
731 case vmIntrinsics::_max:
732 case vmIntrinsics::_min_strict:
733 case vmIntrinsics::_max_strict:
734 case vmIntrinsics::_minL:
735 case vmIntrinsics::_maxL:
736 case vmIntrinsics::_minF:
737 case vmIntrinsics::_maxF:
738 case vmIntrinsics::_minD:
739 case vmIntrinsics::_maxD:
740 case vmIntrinsics::_minF_strict:
741 case vmIntrinsics::_maxF_strict:
742 case vmIntrinsics::_minD_strict:
743 case vmIntrinsics::_maxD_strict:
744 return inline_min_max(intrinsic_id());
745
746 case vmIntrinsics::_VectorUnaryOp:
747 return inline_vector_nary_operation(1);
748 case vmIntrinsics::_VectorBinaryOp:
749 return inline_vector_nary_operation(2);
750 case vmIntrinsics::_VectorUnaryLibOp:
751 return inline_vector_call(1);
752 case vmIntrinsics::_VectorBinaryLibOp:
753 return inline_vector_call(2);
754 case vmIntrinsics::_VectorTernaryOp:
755 return inline_vector_nary_operation(3);
756 case vmIntrinsics::_VectorFromBitsCoerced:
757 return inline_vector_frombits_coerced();
758 case vmIntrinsics::_VectorMaskOp:
759 return inline_vector_mask_operation();
760 case vmIntrinsics::_VectorLoadOp:
761 return inline_vector_mem_operation(/*is_store=*/false);
762 case vmIntrinsics::_VectorLoadMaskedOp:
763 return inline_vector_mem_masked_operation(/*is_store*/false);
764 case vmIntrinsics::_VectorStoreOp:
765 return inline_vector_mem_operation(/*is_store=*/true);
766 case vmIntrinsics::_VectorStoreMaskedOp:
767 return inline_vector_mem_masked_operation(/*is_store=*/true);
768 case vmIntrinsics::_VectorGatherOp:
769 return inline_vector_gather_scatter(/*is_scatter*/ false);
770 case vmIntrinsics::_VectorScatterOp:
771 return inline_vector_gather_scatter(/*is_scatter*/ true);
772 case vmIntrinsics::_VectorReductionCoerced:
773 return inline_vector_reduction();
774 case vmIntrinsics::_VectorTest:
775 return inline_vector_test();
776 case vmIntrinsics::_VectorBlend:
777 return inline_vector_blend();
778 case vmIntrinsics::_VectorRearrange:
779 return inline_vector_rearrange();
780 case vmIntrinsics::_VectorSelectFrom:
781 return inline_vector_select_from();
782 case vmIntrinsics::_VectorCompare:
783 return inline_vector_compare();
784 case vmIntrinsics::_VectorBroadcastInt:
785 return inline_vector_broadcast_int();
786 case vmIntrinsics::_VectorConvert:
787 return inline_vector_convert();
788 case vmIntrinsics::_VectorInsert:
789 return inline_vector_insert();
790 case vmIntrinsics::_VectorExtract:
791 return inline_vector_extract();
792 case vmIntrinsics::_VectorCompressExpand:
793 return inline_vector_compress_expand();
794 case vmIntrinsics::_VectorSelectFromTwoVectorOp:
795 return inline_vector_select_from_two_vectors();
796 case vmIntrinsics::_IndexVector:
797 return inline_index_vector();
798 case vmIntrinsics::_IndexPartiallyInUpperRange:
799 return inline_index_partially_in_upper_range();
800
801 case vmIntrinsics::_getObjectSize:
802 return inline_getObjectSize();
803
804 case vmIntrinsics::_blackhole:
805 return inline_blackhole();
806
807 default:
808 // If you get here, it may be that someone has added a new intrinsic
809 // to the list in vmIntrinsics.hpp without implementing it here.
810 #ifndef PRODUCT
811 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
812 tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
813 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
814 }
815 #endif
816 return false;
817 }
818 }
819
820 Node* LibraryCallKit::try_to_predicate(int predicate) {
821 if (!jvms()->has_method()) {
822 // Root JVMState has a null method.
823 assert(map()->memory()->Opcode() == Op_Parm, "");
824 // Insert the memory aliasing node
825 set_all_memory(reset_memory());
826 }
827 assert(merged_memory(), "");
828
829 switch (intrinsic_id()) {
830 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
831 return inline_cipherBlockChaining_AESCrypt_predicate(false);
832 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
833 return inline_cipherBlockChaining_AESCrypt_predicate(true);
834 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
835 return inline_electronicCodeBook_AESCrypt_predicate(false);
836 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
837 return inline_electronicCodeBook_AESCrypt_predicate(true);
838 case vmIntrinsics::_counterMode_AESCrypt:
839 return inline_counterMode_AESCrypt_predicate();
840 case vmIntrinsics::_digestBase_implCompressMB:
841 return inline_digestBase_implCompressMB_predicate(predicate);
842 case vmIntrinsics::_galoisCounterMode_AESCrypt:
843 return inline_galoisCounterMode_AESCrypt_predicate();
844
845 default:
846 // If you get here, it may be that someone has added a new intrinsic
847 // to the list in vmIntrinsics.hpp without implementing it here.
848 #ifndef PRODUCT
849 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
850 tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
851 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
852 }
853 #endif
854 Node* slow_ctl = control();
855 set_control(top()); // No fast path intrinsic
856 return slow_ctl;
857 }
858 }
859
860 //------------------------------set_result-------------------------------
861 // Helper function for finishing intrinsics.
862 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
863 record_for_igvn(region);
864 set_control(_gvn.transform(region));
865 set_result( _gvn.transform(value));
866 assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
867 }
868
869 //------------------------------generate_guard---------------------------
870 // Helper function for generating guarded fast-slow graph structures.
871 // The given 'test', if true, guards a slow path. If the test fails
872 // then a fast path can be taken. (We generally hope it fails.)
873 // In all cases, GraphKit::control() is updated to the fast path.
874 // The returned value represents the control for the slow path.
875 // The return value is never 'top'; it is either a valid control
876 // or null if it is obvious that the slow path can never be taken.
877 // Also, if region and the slow control are not null, the slow edge
878 // is appended to the region.
879 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
880 if (stopped()) {
881 // Already short circuited.
882 return nullptr;
883 }
884
885 // Build an if node and its projections.
886 // If test is true we take the slow path, which we assume is uncommon.
887 if (_gvn.type(test) == TypeInt::ZERO) {
888 // The slow branch is never taken. No need to build this guard.
889 return nullptr;
890 }
891
892 IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
893
894 Node* if_slow = _gvn.transform(new IfTrueNode(iff));
895 if (if_slow == top()) {
896 // The slow branch is never taken. No need to build this guard.
897 return nullptr;
898 }
899
900 if (region != nullptr)
901 region->add_req(if_slow);
902
903 Node* if_fast = _gvn.transform(new IfFalseNode(iff));
904 set_control(if_fast);
905
906 return if_slow;
907 }
908
909 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
910 return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
911 }
912 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
913 return generate_guard(test, region, PROB_FAIR);
914 }
915
916 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
917 Node* *pos_index) {
918 if (stopped())
919 return nullptr; // already stopped
920 if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
921 return nullptr; // index is already adequately typed
922 Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
923 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
924 Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
925 if (is_neg != nullptr && pos_index != nullptr) {
926 // Emulate effect of Parse::adjust_map_after_if.
927 Node* ccast = new CastIINode(control(), index, TypeInt::POS);
928 (*pos_index) = _gvn.transform(ccast);
929 }
930 return is_neg;
931 }
932
933 // Make sure that 'position' is a valid limit index, in [0..length].
934 // There are two equivalent plans for checking this:
935 // A. (offset + copyLength) unsigned<= arrayLength
936 // B. offset <= (arrayLength - copyLength)
937 // We require that all of the values above, except for the sum and
938 // difference, are already known to be non-negative.
939 // Plan A is robust in the face of overflow, if offset and copyLength
940 // are both hugely positive.
941 //
942 // Plan B is less direct and intuitive, but it does not overflow at
943 // all, since the difference of two non-negatives is always
944 // representable. Whenever Java methods must perform the equivalent
945 // check they generally use Plan B instead of Plan A.
946 // For the moment we use Plan A.
947 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
948 Node* subseq_length,
949 Node* array_length,
950 RegionNode* region) {
951 if (stopped())
952 return nullptr; // already stopped
953 bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
954 if (zero_offset && subseq_length->eqv_uncast(array_length))
955 return nullptr; // common case of whole-array copy
956 Node* last = subseq_length;
957 if (!zero_offset) // last += offset
958 last = _gvn.transform(new AddINode(last, offset));
959 Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
960 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
961 Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
962 return is_over;
963 }
964
965 // Emit range checks for the given String.value byte array
966 void LibraryCallKit::generate_string_range_check(Node* array,
967 Node* offset,
968 Node* count,
969 bool char_count,
970 bool halt_on_oob) {
971 if (stopped()) {
972 return; // already stopped
973 }
974 RegionNode* bailout = new RegionNode(1);
975 record_for_igvn(bailout);
976 if (char_count) {
977 // Convert char count to byte count
978 count = _gvn.transform(new LShiftINode(count, intcon(1)));
979 }
980
981 // Offset and count must not be negative
982 generate_negative_guard(offset, bailout);
983 generate_negative_guard(count, bailout);
984 // Offset + count must not exceed length of array
985 generate_limit_guard(offset, count, load_array_length(array), bailout);
986
987 if (bailout->req() > 1) {
988 if (halt_on_oob) {
989 bailout = _gvn.transform(bailout)->as_Region();
990 Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
991 Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
992 C->root()->add_req(halt);
993 } else {
994 PreserveJVMState pjvms(this);
995 set_control(_gvn.transform(bailout));
996 uncommon_trap(Deoptimization::Reason_intrinsic,
997 Deoptimization::Action_maybe_recompile);
998 }
999 }
1000 }
1001
1002 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1003 bool is_immutable) {
1004 ciKlass* thread_klass = env()->Thread_klass();
1005 const Type* thread_type
1006 = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1007
1008 Node* thread = _gvn.transform(new ThreadLocalNode());
1009 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1010 tls_output = thread;
1011
1012 Node* thread_obj_handle
1013 = (is_immutable
1014 ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1015 TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1016 : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1017 thread_obj_handle = _gvn.transform(thread_obj_handle);
1018
1019 DecoratorSet decorators = IN_NATIVE;
1020 if (is_immutable) {
1021 decorators |= C2_IMMUTABLE_MEMORY;
1022 }
1023 return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1024 }
1025
1026 //--------------------------generate_current_thread--------------------
1027 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1028 return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1029 /*is_immutable*/false);
1030 }
1031
1032 //--------------------------generate_virtual_thread--------------------
1033 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1034 return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1035 !C->method()->changes_current_thread());
1036 }
1037
1038 //------------------------------make_string_method_node------------------------
1039 // Helper method for String intrinsic functions. This version is called with
1040 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1041 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1042 // containing the lengths of str1 and str2.
1043 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1044 Node* result = nullptr;
1045 switch (opcode) {
1046 case Op_StrIndexOf:
1047 result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1048 str1_start, cnt1, str2_start, cnt2, ae);
1049 break;
1050 case Op_StrComp:
1051 result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1052 str1_start, cnt1, str2_start, cnt2, ae);
1053 break;
1054 case Op_StrEquals:
1055 // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1056 // Use the constant length if there is one because optimized match rule may exist.
1057 result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1058 str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1059 break;
1060 default:
1061 ShouldNotReachHere();
1062 return nullptr;
1063 }
1064
1065 // All these intrinsics have checks.
1066 C->set_has_split_ifs(true); // Has chance for split-if optimization
1067 clear_upper_avx();
1068
1069 return _gvn.transform(result);
1070 }
1071
1072 //------------------------------inline_string_compareTo------------------------
1073 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1074 Node* arg1 = argument(0);
1075 Node* arg2 = argument(1);
1076
1077 arg1 = must_be_not_null(arg1, true);
1078 arg2 = must_be_not_null(arg2, true);
1079
1080 // Get start addr and length of first argument
1081 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1082 Node* arg1_cnt = load_array_length(arg1);
1083
1084 // Get start addr and length of second argument
1085 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1086 Node* arg2_cnt = load_array_length(arg2);
1087
1088 Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1089 set_result(result);
1090 return true;
1091 }
1092
1093 //------------------------------inline_string_equals------------------------
1094 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1095 Node* arg1 = argument(0);
1096 Node* arg2 = argument(1);
1097
1098 // paths (plus control) merge
1099 RegionNode* region = new RegionNode(3);
1100 Node* phi = new PhiNode(region, TypeInt::BOOL);
1101
1102 if (!stopped()) {
1103
1104 arg1 = must_be_not_null(arg1, true);
1105 arg2 = must_be_not_null(arg2, true);
1106
1107 // Get start addr and length of first argument
1108 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1109 Node* arg1_cnt = load_array_length(arg1);
1110
1111 // Get start addr and length of second argument
1112 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1113 Node* arg2_cnt = load_array_length(arg2);
1114
1115 // Check for arg1_cnt != arg2_cnt
1116 Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1117 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1118 Node* if_ne = generate_slow_guard(bol, nullptr);
1119 if (if_ne != nullptr) {
1120 phi->init_req(2, intcon(0));
1121 region->init_req(2, if_ne);
1122 }
1123
1124 // Check for count == 0 is done by assembler code for StrEquals.
1125
1126 if (!stopped()) {
1127 Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1128 phi->init_req(1, equals);
1129 region->init_req(1, control());
1130 }
1131 }
1132
1133 // post merge
1134 set_control(_gvn.transform(region));
1135 record_for_igvn(region);
1136
1137 set_result(_gvn.transform(phi));
1138 return true;
1139 }
1140
1141 //------------------------------inline_array_equals----------------------------
1142 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1143 assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1144 Node* arg1 = argument(0);
1145 Node* arg2 = argument(1);
1146
1147 const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1148 set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1149 clear_upper_avx();
1150
1151 return true;
1152 }
1153
1154
1155 //------------------------------inline_countPositives------------------------------
1156 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1157 bool LibraryCallKit::inline_countPositives() {
1158 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1159 return false;
1160 }
1161
1162 assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1163 // no receiver since it is static method
1164 Node* ba = argument(0);
1165 Node* offset = argument(1);
1166 Node* len = argument(2);
1167
1168 if (VerifyIntrinsicChecks) {
1169 ba = must_be_not_null(ba, true);
1170 generate_string_range_check(ba, offset, len, false, true);
1171 if (stopped()) {
1172 return true;
1173 }
1174 }
1175
1176 Node* ba_start = array_element_address(ba, offset, T_BYTE);
1177 Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1178 set_result(_gvn.transform(result));
1179 clear_upper_avx();
1180 return true;
1181 }
1182
1183 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1184 Node* index = argument(0);
1185 Node* length = bt == T_INT ? argument(1) : argument(2);
1186 if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1187 return false;
1188 }
1189
1190 // check that length is positive
1191 Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1192 Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1193
1194 {
1195 BuildCutout unless(this, len_pos_bol, PROB_MAX);
1196 uncommon_trap(Deoptimization::Reason_intrinsic,
1197 Deoptimization::Action_make_not_entrant);
1198 }
1199
1200 if (stopped()) {
1201 // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1202 return true;
1203 }
1204
1205 // length is now known positive, add a cast node to make this explicit
1206 jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1207 Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1208 control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1209 ConstraintCastNode::RegularDependency, bt);
1210 casted_length = _gvn.transform(casted_length);
1211 replace_in_map(length, casted_length);
1212 length = casted_length;
1213
1214 // Use an unsigned comparison for the range check itself
1215 Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1216 BoolTest::mask btest = BoolTest::lt;
1217 Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1218 RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1219 _gvn.set_type(rc, rc->Value(&_gvn));
1220 if (!rc_bool->is_Con()) {
1221 record_for_igvn(rc);
1222 }
1223 set_control(_gvn.transform(new IfTrueNode(rc)));
1224 {
1225 PreserveJVMState pjvms(this);
1226 set_control(_gvn.transform(new IfFalseNode(rc)));
1227 uncommon_trap(Deoptimization::Reason_range_check,
1228 Deoptimization::Action_make_not_entrant);
1229 }
1230
1231 if (stopped()) {
1232 // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1233 return true;
1234 }
1235
1236 // index is now known to be >= 0 and < length, cast it
1237 Node* result = ConstraintCastNode::make_cast_for_basic_type(
1238 control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1239 ConstraintCastNode::RegularDependency, bt);
1240 result = _gvn.transform(result);
1241 set_result(result);
1242 replace_in_map(index, result);
1243 return true;
1244 }
1245
1246 //------------------------------inline_string_indexOf------------------------
1247 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1248 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1249 return false;
1250 }
1251 Node* src = argument(0);
1252 Node* tgt = argument(1);
1253
1254 // Make the merge point
1255 RegionNode* result_rgn = new RegionNode(4);
1256 Node* result_phi = new PhiNode(result_rgn, TypeInt::INT);
1257
1258 src = must_be_not_null(src, true);
1259 tgt = must_be_not_null(tgt, true);
1260
1261 // Get start addr and length of source string
1262 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1263 Node* src_count = load_array_length(src);
1264
1265 // Get start addr and length of substring
1266 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1267 Node* tgt_count = load_array_length(tgt);
1268
1269 Node* result = nullptr;
1270 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1271
1272 if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1273 // Divide src size by 2 if String is UTF16 encoded
1274 src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1275 }
1276 if (ae == StrIntrinsicNode::UU) {
1277 // Divide substring size by 2 if String is UTF16 encoded
1278 tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1279 }
1280
1281 if (call_opt_stub) {
1282 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1283 StubRoutines::_string_indexof_array[ae],
1284 "stringIndexOf", TypePtr::BOTTOM, src_start,
1285 src_count, tgt_start, tgt_count);
1286 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1287 } else {
1288 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1289 result_rgn, result_phi, ae);
1290 }
1291 if (result != nullptr) {
1292 result_phi->init_req(3, result);
1293 result_rgn->init_req(3, control());
1294 }
1295 set_control(_gvn.transform(result_rgn));
1296 record_for_igvn(result_rgn);
1297 set_result(_gvn.transform(result_phi));
1298
1299 return true;
1300 }
1301
1302 //-----------------------------inline_string_indexOfI-----------------------
1303 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1304 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1305 return false;
1306 }
1307 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1308 return false;
1309 }
1310
1311 assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1312 Node* src = argument(0); // byte[]
1313 Node* src_count = argument(1); // char count
1314 Node* tgt = argument(2); // byte[]
1315 Node* tgt_count = argument(3); // char count
1316 Node* from_index = argument(4); // char index
1317
1318 src = must_be_not_null(src, true);
1319 tgt = must_be_not_null(tgt, true);
1320
1321 // Multiply byte array index by 2 if String is UTF16 encoded
1322 Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1323 src_count = _gvn.transform(new SubINode(src_count, from_index));
1324 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1325 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1326
1327 // Range checks
1328 generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1329 generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1330 if (stopped()) {
1331 return true;
1332 }
1333
1334 RegionNode* region = new RegionNode(5);
1335 Node* phi = new PhiNode(region, TypeInt::INT);
1336 Node* result = nullptr;
1337
1338 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1339
1340 if (call_opt_stub) {
1341 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1342 StubRoutines::_string_indexof_array[ae],
1343 "stringIndexOf", TypePtr::BOTTOM, src_start,
1344 src_count, tgt_start, tgt_count);
1345 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1346 } else {
1347 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1348 region, phi, ae);
1349 }
1350 if (result != nullptr) {
1351 // The result is index relative to from_index if substring was found, -1 otherwise.
1352 // Generate code which will fold into cmove.
1353 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1354 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1355
1356 Node* if_lt = generate_slow_guard(bol, nullptr);
1357 if (if_lt != nullptr) {
1358 // result == -1
1359 phi->init_req(3, result);
1360 region->init_req(3, if_lt);
1361 }
1362 if (!stopped()) {
1363 result = _gvn.transform(new AddINode(result, from_index));
1364 phi->init_req(4, result);
1365 region->init_req(4, control());
1366 }
1367 }
1368
1369 set_control(_gvn.transform(region));
1370 record_for_igvn(region);
1371 set_result(_gvn.transform(phi));
1372 clear_upper_avx();
1373
1374 return true;
1375 }
1376
1377 // Create StrIndexOfNode with fast path checks
1378 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1379 RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1380 // Check for substr count > string count
1381 Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1382 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1383 Node* if_gt = generate_slow_guard(bol, nullptr);
1384 if (if_gt != nullptr) {
1385 phi->init_req(1, intcon(-1));
1386 region->init_req(1, if_gt);
1387 }
1388 if (!stopped()) {
1389 // Check for substr count == 0
1390 cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1391 bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1392 Node* if_zero = generate_slow_guard(bol, nullptr);
1393 if (if_zero != nullptr) {
1394 phi->init_req(2, intcon(0));
1395 region->init_req(2, if_zero);
1396 }
1397 }
1398 if (!stopped()) {
1399 return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1400 }
1401 return nullptr;
1402 }
1403
1404 //-----------------------------inline_string_indexOfChar-----------------------
1405 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1406 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1407 return false;
1408 }
1409 if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1410 return false;
1411 }
1412 assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1413 Node* src = argument(0); // byte[]
1414 Node* int_ch = argument(1);
1415 Node* from_index = argument(2);
1416 Node* max = argument(3);
1417
1418 src = must_be_not_null(src, true);
1419
1420 Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1421 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1422 Node* src_count = _gvn.transform(new SubINode(max, from_index));
1423
1424 // Range checks
1425 generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1426
1427 // Check for int_ch >= 0
1428 Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1429 Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1430 {
1431 BuildCutout unless(this, int_ch_bol, PROB_MAX);
1432 uncommon_trap(Deoptimization::Reason_intrinsic,
1433 Deoptimization::Action_maybe_recompile);
1434 }
1435 if (stopped()) {
1436 return true;
1437 }
1438
1439 RegionNode* region = new RegionNode(3);
1440 Node* phi = new PhiNode(region, TypeInt::INT);
1441
1442 Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1443 C->set_has_split_ifs(true); // Has chance for split-if optimization
1444 _gvn.transform(result);
1445
1446 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1447 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1448
1449 Node* if_lt = generate_slow_guard(bol, nullptr);
1450 if (if_lt != nullptr) {
1451 // result == -1
1452 phi->init_req(2, result);
1453 region->init_req(2, if_lt);
1454 }
1455 if (!stopped()) {
1456 result = _gvn.transform(new AddINode(result, from_index));
1457 phi->init_req(1, result);
1458 region->init_req(1, control());
1459 }
1460 set_control(_gvn.transform(region));
1461 record_for_igvn(region);
1462 set_result(_gvn.transform(phi));
1463 clear_upper_avx();
1464
1465 return true;
1466 }
1467 //---------------------------inline_string_copy---------------------
1468 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1469 // int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1470 // int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1471 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1472 // void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1473 // void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1474 bool LibraryCallKit::inline_string_copy(bool compress) {
1475 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1476 return false;
1477 }
1478 int nargs = 5; // 2 oops, 3 ints
1479 assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1480
1481 Node* src = argument(0);
1482 Node* src_offset = argument(1);
1483 Node* dst = argument(2);
1484 Node* dst_offset = argument(3);
1485 Node* length = argument(4);
1486
1487 // Check for allocation before we add nodes that would confuse
1488 // tightly_coupled_allocation()
1489 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1490
1491 // Figure out the size and type of the elements we will be copying.
1492 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1493 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1494 if (src_type == nullptr || dst_type == nullptr) {
1495 return false;
1496 }
1497 BasicType src_elem = src_type->elem()->array_element_basic_type();
1498 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1499 assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1500 (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1501 "Unsupported array types for inline_string_copy");
1502
1503 src = must_be_not_null(src, true);
1504 dst = must_be_not_null(dst, true);
1505
1506 // Convert char[] offsets to byte[] offsets
1507 bool convert_src = (compress && src_elem == T_BYTE);
1508 bool convert_dst = (!compress && dst_elem == T_BYTE);
1509 if (convert_src) {
1510 src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1511 } else if (convert_dst) {
1512 dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1513 }
1514
1515 // Range checks
1516 generate_string_range_check(src, src_offset, length, convert_src);
1517 generate_string_range_check(dst, dst_offset, length, convert_dst);
1518 if (stopped()) {
1519 return true;
1520 }
1521
1522 Node* src_start = array_element_address(src, src_offset, src_elem);
1523 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1524 // 'src_start' points to src array + scaled offset
1525 // 'dst_start' points to dst array + scaled offset
1526 Node* count = nullptr;
1527 if (compress) {
1528 count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1529 } else {
1530 inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1531 }
1532
1533 if (alloc != nullptr) {
1534 if (alloc->maybe_set_complete(&_gvn)) {
1535 // "You break it, you buy it."
1536 InitializeNode* init = alloc->initialization();
1537 assert(init->is_complete(), "we just did this");
1538 init->set_complete_with_arraycopy();
1539 assert(dst->is_CheckCastPP(), "sanity");
1540 assert(dst->in(0)->in(0) == init, "dest pinned");
1541 }
1542 // Do not let stores that initialize this object be reordered with
1543 // a subsequent store that would make this object accessible by
1544 // other threads.
1545 // Record what AllocateNode this StoreStore protects so that
1546 // escape analysis can go from the MemBarStoreStoreNode to the
1547 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1548 // based on the escape status of the AllocateNode.
1549 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1550 }
1551 if (compress) {
1552 set_result(_gvn.transform(count));
1553 }
1554 clear_upper_avx();
1555
1556 return true;
1557 }
1558
1559 #ifdef _LP64
1560 #define XTOP ,top() /*additional argument*/
1561 #else //_LP64
1562 #define XTOP /*no additional argument*/
1563 #endif //_LP64
1564
1565 //------------------------inline_string_toBytesU--------------------------
1566 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1567 bool LibraryCallKit::inline_string_toBytesU() {
1568 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1569 return false;
1570 }
1571 // Get the arguments.
1572 Node* value = argument(0);
1573 Node* offset = argument(1);
1574 Node* length = argument(2);
1575
1576 Node* newcopy = nullptr;
1577
1578 // Set the original stack and the reexecute bit for the interpreter to reexecute
1579 // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1580 { PreserveReexecuteState preexecs(this);
1581 jvms()->set_should_reexecute(true);
1582
1583 // Check if a null path was taken unconditionally.
1584 value = null_check(value);
1585
1586 RegionNode* bailout = new RegionNode(1);
1587 record_for_igvn(bailout);
1588
1589 // Range checks
1590 generate_negative_guard(offset, bailout);
1591 generate_negative_guard(length, bailout);
1592 generate_limit_guard(offset, length, load_array_length(value), bailout);
1593 // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1594 generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1595
1596 if (bailout->req() > 1) {
1597 PreserveJVMState pjvms(this);
1598 set_control(_gvn.transform(bailout));
1599 uncommon_trap(Deoptimization::Reason_intrinsic,
1600 Deoptimization::Action_maybe_recompile);
1601 }
1602 if (stopped()) {
1603 return true;
1604 }
1605
1606 Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1607 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1608 newcopy = new_array(klass_node, size, 0); // no arguments to push
1609 AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1610 guarantee(alloc != nullptr, "created above");
1611
1612 // Calculate starting addresses.
1613 Node* src_start = array_element_address(value, offset, T_CHAR);
1614 Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1615
1616 // Check if dst array address is aligned to HeapWordSize
1617 bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1618 // If true, then check if src array address is aligned to HeapWordSize
1619 if (aligned) {
1620 const TypeInt* toffset = gvn().type(offset)->is_int();
1621 aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1622 toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1623 }
1624
1625 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1626 const char* copyfunc_name = "arraycopy";
1627 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1628 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1629 OptoRuntime::fast_arraycopy_Type(),
1630 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1631 src_start, dst_start, ConvI2X(length) XTOP);
1632 // Do not let reads from the cloned object float above the arraycopy.
1633 if (alloc->maybe_set_complete(&_gvn)) {
1634 // "You break it, you buy it."
1635 InitializeNode* init = alloc->initialization();
1636 assert(init->is_complete(), "we just did this");
1637 init->set_complete_with_arraycopy();
1638 assert(newcopy->is_CheckCastPP(), "sanity");
1639 assert(newcopy->in(0)->in(0) == init, "dest pinned");
1640 }
1641 // Do not let stores that initialize this object be reordered with
1642 // a subsequent store that would make this object accessible by
1643 // other threads.
1644 // Record what AllocateNode this StoreStore protects so that
1645 // escape analysis can go from the MemBarStoreStoreNode to the
1646 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1647 // based on the escape status of the AllocateNode.
1648 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1649 } // original reexecute is set back here
1650
1651 C->set_has_split_ifs(true); // Has chance for split-if optimization
1652 if (!stopped()) {
1653 set_result(newcopy);
1654 }
1655 clear_upper_avx();
1656
1657 return true;
1658 }
1659
1660 //------------------------inline_string_getCharsU--------------------------
1661 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1662 bool LibraryCallKit::inline_string_getCharsU() {
1663 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1664 return false;
1665 }
1666
1667 // Get the arguments.
1668 Node* src = argument(0);
1669 Node* src_begin = argument(1);
1670 Node* src_end = argument(2); // exclusive offset (i < src_end)
1671 Node* dst = argument(3);
1672 Node* dst_begin = argument(4);
1673
1674 // Check for allocation before we add nodes that would confuse
1675 // tightly_coupled_allocation()
1676 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1677
1678 // Check if a null path was taken unconditionally.
1679 src = null_check(src);
1680 dst = null_check(dst);
1681 if (stopped()) {
1682 return true;
1683 }
1684
1685 // Get length and convert char[] offset to byte[] offset
1686 Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1687 src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1688
1689 // Range checks
1690 generate_string_range_check(src, src_begin, length, true);
1691 generate_string_range_check(dst, dst_begin, length, false);
1692 if (stopped()) {
1693 return true;
1694 }
1695
1696 if (!stopped()) {
1697 // Calculate starting addresses.
1698 Node* src_start = array_element_address(src, src_begin, T_BYTE);
1699 Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1700
1701 // Check if array addresses are aligned to HeapWordSize
1702 const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1703 const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1704 bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1705 tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1706
1707 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1708 const char* copyfunc_name = "arraycopy";
1709 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1710 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1711 OptoRuntime::fast_arraycopy_Type(),
1712 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1713 src_start, dst_start, ConvI2X(length) XTOP);
1714 // Do not let reads from the cloned object float above the arraycopy.
1715 if (alloc != nullptr) {
1716 if (alloc->maybe_set_complete(&_gvn)) {
1717 // "You break it, you buy it."
1718 InitializeNode* init = alloc->initialization();
1719 assert(init->is_complete(), "we just did this");
1720 init->set_complete_with_arraycopy();
1721 assert(dst->is_CheckCastPP(), "sanity");
1722 assert(dst->in(0)->in(0) == init, "dest pinned");
1723 }
1724 // Do not let stores that initialize this object be reordered with
1725 // a subsequent store that would make this object accessible by
1726 // other threads.
1727 // Record what AllocateNode this StoreStore protects so that
1728 // escape analysis can go from the MemBarStoreStoreNode to the
1729 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1730 // based on the escape status of the AllocateNode.
1731 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1732 } else {
1733 insert_mem_bar(Op_MemBarCPUOrder);
1734 }
1735 }
1736
1737 C->set_has_split_ifs(true); // Has chance for split-if optimization
1738 return true;
1739 }
1740
1741 //----------------------inline_string_char_access----------------------------
1742 // Store/Load char to/from byte[] array.
1743 // static void StringUTF16.putChar(byte[] val, int index, int c)
1744 // static char StringUTF16.getChar(byte[] val, int index)
1745 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1746 Node* value = argument(0);
1747 Node* index = argument(1);
1748 Node* ch = is_store ? argument(2) : nullptr;
1749
1750 // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1751 // correctly requires matched array shapes.
1752 assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1753 "sanity: byte[] and char[] bases agree");
1754 assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1755 "sanity: byte[] and char[] scales agree");
1756
1757 // Bail when getChar over constants is requested: constant folding would
1758 // reject folding mismatched char access over byte[]. A normal inlining for getChar
1759 // Java method would constant fold nicely instead.
1760 if (!is_store && value->is_Con() && index->is_Con()) {
1761 return false;
1762 }
1763
1764 // Save state and restore on bailout
1765 SavedState old_state(this);
1766
1767 value = must_be_not_null(value, true);
1768
1769 Node* adr = array_element_address(value, index, T_CHAR);
1770 if (adr->is_top()) {
1771 return false;
1772 }
1773 old_state.discard();
1774 if (is_store) {
1775 access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1776 } else {
1777 ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1778 set_result(ch);
1779 }
1780 return true;
1781 }
1782
1783
1784 //------------------------------inline_math-----------------------------------
1785 // public static double Math.abs(double)
1786 // public static double Math.sqrt(double)
1787 // public static double Math.log(double)
1788 // public static double Math.log10(double)
1789 // public static double Math.round(double)
1790 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1791 Node* arg = argument(0);
1792 Node* n = nullptr;
1793 switch (id) {
1794 case vmIntrinsics::_dabs: n = new AbsDNode( arg); break;
1795 case vmIntrinsics::_dsqrt:
1796 case vmIntrinsics::_dsqrt_strict:
1797 n = new SqrtDNode(C, control(), arg); break;
1798 case vmIntrinsics::_ceil: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1799 case vmIntrinsics::_floor: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1800 case vmIntrinsics::_rint: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1801 case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1802 case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1803 case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1804 default: fatal_unexpected_iid(id); break;
1805 }
1806 set_result(_gvn.transform(n));
1807 return true;
1808 }
1809
1810 //------------------------------inline_math-----------------------------------
1811 // public static float Math.abs(float)
1812 // public static int Math.abs(int)
1813 // public static long Math.abs(long)
1814 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1815 Node* arg = argument(0);
1816 Node* n = nullptr;
1817 switch (id) {
1818 case vmIntrinsics::_fabs: n = new AbsFNode( arg); break;
1819 case vmIntrinsics::_iabs: n = new AbsINode( arg); break;
1820 case vmIntrinsics::_labs: n = new AbsLNode( arg); break;
1821 case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1822 case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1823 case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1824 default: fatal_unexpected_iid(id); break;
1825 }
1826 set_result(_gvn.transform(n));
1827 return true;
1828 }
1829
1830 //------------------------------runtime_math-----------------------------
1831 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1832 assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1833 "must be (DD)D or (D)D type");
1834
1835 // Inputs
1836 Node* a = argument(0);
1837 Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1838
1839 const TypePtr* no_memory_effects = nullptr;
1840 Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1841 no_memory_effects,
1842 a, top(), b, b ? top() : nullptr);
1843 Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1844 #ifdef ASSERT
1845 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1846 assert(value_top == top(), "second value must be top");
1847 #endif
1848
1849 set_result(value);
1850 return true;
1851 }
1852
1853 //------------------------------inline_math_pow-----------------------------
1854 bool LibraryCallKit::inline_math_pow() {
1855 Node* exp = argument(2);
1856 const TypeD* d = _gvn.type(exp)->isa_double_constant();
1857 if (d != nullptr) {
1858 if (d->getd() == 2.0) {
1859 // Special case: pow(x, 2.0) => x * x
1860 Node* base = argument(0);
1861 set_result(_gvn.transform(new MulDNode(base, base)));
1862 return true;
1863 } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1864 // Special case: pow(x, 0.5) => sqrt(x)
1865 Node* base = argument(0);
1866 Node* zero = _gvn.zerocon(T_DOUBLE);
1867
1868 RegionNode* region = new RegionNode(3);
1869 Node* phi = new PhiNode(region, Type::DOUBLE);
1870
1871 Node* cmp = _gvn.transform(new CmpDNode(base, zero));
1872 // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1873 // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1874 // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1875 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1876
1877 Node* if_pow = generate_slow_guard(test, nullptr);
1878 Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1879 phi->init_req(1, value_sqrt);
1880 region->init_req(1, control());
1881
1882 if (if_pow != nullptr) {
1883 set_control(if_pow);
1884 address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1885 CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1886 const TypePtr* no_memory_effects = nullptr;
1887 Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1888 no_memory_effects, base, top(), exp, top());
1889 Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1890 #ifdef ASSERT
1891 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1892 assert(value_top == top(), "second value must be top");
1893 #endif
1894 phi->init_req(2, value_pow);
1895 region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1896 }
1897
1898 C->set_has_split_ifs(true); // Has chance for split-if optimization
1899 set_control(_gvn.transform(region));
1900 record_for_igvn(region);
1901 set_result(_gvn.transform(phi));
1902
1903 return true;
1904 }
1905 }
1906
1907 return StubRoutines::dpow() != nullptr ?
1908 runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(), "dpow") :
1909 runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow), "POW");
1910 }
1911
1912 //------------------------------inline_math_native-----------------------------
1913 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1914 switch (id) {
1915 case vmIntrinsics::_dsin:
1916 return StubRoutines::dsin() != nullptr ?
1917 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1918 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1919 case vmIntrinsics::_dcos:
1920 return StubRoutines::dcos() != nullptr ?
1921 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1922 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1923 case vmIntrinsics::_dtan:
1924 return StubRoutines::dtan() != nullptr ?
1925 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1926 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1927 case vmIntrinsics::_dsinh:
1928 return StubRoutines::dsinh() != nullptr ?
1929 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1930 case vmIntrinsics::_dtanh:
1931 return StubRoutines::dtanh() != nullptr ?
1932 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1933 case vmIntrinsics::_dcbrt:
1934 return StubRoutines::dcbrt() != nullptr ?
1935 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1936 case vmIntrinsics::_dexp:
1937 return StubRoutines::dexp() != nullptr ?
1938 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(), "dexp") :
1939 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1940 case vmIntrinsics::_dlog:
1941 return StubRoutines::dlog() != nullptr ?
1942 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1943 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1944 case vmIntrinsics::_dlog10:
1945 return StubRoutines::dlog10() != nullptr ?
1946 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1947 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1948
1949 case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1950 case vmIntrinsics::_ceil:
1951 case vmIntrinsics::_floor:
1952 case vmIntrinsics::_rint: return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1953
1954 case vmIntrinsics::_dsqrt:
1955 case vmIntrinsics::_dsqrt_strict:
1956 return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1957 case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_double_math(id) : false;
1958 case vmIntrinsics::_fabs: return Matcher::match_rule_supported(Op_AbsF) ? inline_math(id) : false;
1959 case vmIntrinsics::_iabs: return Matcher::match_rule_supported(Op_AbsI) ? inline_math(id) : false;
1960 case vmIntrinsics::_labs: return Matcher::match_rule_supported(Op_AbsL) ? inline_math(id) : false;
1961
1962 case vmIntrinsics::_dpow: return inline_math_pow();
1963 case vmIntrinsics::_dcopySign: return inline_double_math(id);
1964 case vmIntrinsics::_fcopySign: return inline_math(id);
1965 case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1966 case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1967 case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1968
1969 // These intrinsics are not yet correctly implemented
1970 case vmIntrinsics::_datan2:
1971 return false;
1972
1973 default:
1974 fatal_unexpected_iid(id);
1975 return false;
1976 }
1977 }
1978
1979 //----------------------------inline_notify-----------------------------------*
1980 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1981 const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1982 address func;
1983 if (id == vmIntrinsics::_notify) {
1984 func = OptoRuntime::monitor_notify_Java();
1985 } else {
1986 func = OptoRuntime::monitor_notifyAll_Java();
1987 }
1988 Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1989 make_slow_call_ex(call, env()->Throwable_klass(), false);
1990 return true;
1991 }
1992
1993
1994 //----------------------------inline_min_max-----------------------------------
1995 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1996 Node* a = nullptr;
1997 Node* b = nullptr;
1998 Node* n = nullptr;
1999 switch (id) {
2000 case vmIntrinsics::_min:
2001 case vmIntrinsics::_max:
2002 case vmIntrinsics::_minF:
2003 case vmIntrinsics::_maxF:
2004 case vmIntrinsics::_minF_strict:
2005 case vmIntrinsics::_maxF_strict:
2006 case vmIntrinsics::_min_strict:
2007 case vmIntrinsics::_max_strict:
2008 assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
2009 a = argument(0);
2010 b = argument(1);
2011 break;
2012 case vmIntrinsics::_minD:
2013 case vmIntrinsics::_maxD:
2014 case vmIntrinsics::_minD_strict:
2015 case vmIntrinsics::_maxD_strict:
2016 assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2017 a = argument(0);
2018 b = argument(2);
2019 break;
2020 case vmIntrinsics::_minL:
2021 case vmIntrinsics::_maxL:
2022 assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2023 a = argument(0);
2024 b = argument(2);
2025 break;
2026 default:
2027 fatal_unexpected_iid(id);
2028 break;
2029 }
2030
2031 switch (id) {
2032 case vmIntrinsics::_min:
2033 case vmIntrinsics::_min_strict:
2034 n = new MinINode(a, b);
2035 break;
2036 case vmIntrinsics::_max:
2037 case vmIntrinsics::_max_strict:
2038 n = new MaxINode(a, b);
2039 break;
2040 case vmIntrinsics::_minF:
2041 case vmIntrinsics::_minF_strict:
2042 n = new MinFNode(a, b);
2043 break;
2044 case vmIntrinsics::_maxF:
2045 case vmIntrinsics::_maxF_strict:
2046 n = new MaxFNode(a, b);
2047 break;
2048 case vmIntrinsics::_minD:
2049 case vmIntrinsics::_minD_strict:
2050 n = new MinDNode(a, b);
2051 break;
2052 case vmIntrinsics::_maxD:
2053 case vmIntrinsics::_maxD_strict:
2054 n = new MaxDNode(a, b);
2055 break;
2056 case vmIntrinsics::_minL:
2057 n = new MinLNode(_gvn.C, a, b);
2058 break;
2059 case vmIntrinsics::_maxL:
2060 n = new MaxLNode(_gvn.C, a, b);
2061 break;
2062 default:
2063 fatal_unexpected_iid(id);
2064 break;
2065 }
2066
2067 set_result(_gvn.transform(n));
2068 return true;
2069 }
2070
2071 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2072 if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2073 env()->ArithmeticException_instance())) {
2074 // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2075 // so let's bail out intrinsic rather than risking deopting again.
2076 return false;
2077 }
2078
2079 Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2080 IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2081 Node* fast_path = _gvn.transform( new IfFalseNode(check));
2082 Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2083
2084 {
2085 PreserveJVMState pjvms(this);
2086 PreserveReexecuteState preexecs(this);
2087 jvms()->set_should_reexecute(true);
2088
2089 set_control(slow_path);
2090 set_i_o(i_o());
2091
2092 builtin_throw(Deoptimization::Reason_intrinsic,
2093 env()->ArithmeticException_instance(),
2094 /*allow_too_many_traps*/ false);
2095 }
2096
2097 set_control(fast_path);
2098 set_result(math);
2099 return true;
2100 }
2101
2102 template <typename OverflowOp>
2103 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2104 typedef typename OverflowOp::MathOp MathOp;
2105
2106 MathOp* mathOp = new MathOp(arg1, arg2);
2107 Node* operation = _gvn.transform( mathOp );
2108 Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2109 return inline_math_mathExact(operation, ofcheck);
2110 }
2111
2112 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2113 return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2114 }
2115
2116 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2117 return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2118 }
2119
2120 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2121 return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2122 }
2123
2124 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2125 return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2126 }
2127
2128 bool LibraryCallKit::inline_math_negateExactI() {
2129 return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2130 }
2131
2132 bool LibraryCallKit::inline_math_negateExactL() {
2133 return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2134 }
2135
2136 bool LibraryCallKit::inline_math_multiplyExactI() {
2137 return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2138 }
2139
2140 bool LibraryCallKit::inline_math_multiplyExactL() {
2141 return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2142 }
2143
2144 bool LibraryCallKit::inline_math_multiplyHigh() {
2145 set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2146 return true;
2147 }
2148
2149 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2150 set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2151 return true;
2152 }
2153
2154 inline int
2155 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2156 const TypePtr* base_type = TypePtr::NULL_PTR;
2157 if (base != nullptr) base_type = _gvn.type(base)->isa_ptr();
2158 if (base_type == nullptr) {
2159 // Unknown type.
2160 return Type::AnyPtr;
2161 } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2162 // Since this is a null+long form, we have to switch to a rawptr.
2163 base = _gvn.transform(new CastX2PNode(offset));
2164 offset = MakeConX(0);
2165 return Type::RawPtr;
2166 } else if (base_type->base() == Type::RawPtr) {
2167 return Type::RawPtr;
2168 } else if (base_type->isa_oopptr()) {
2169 // Base is never null => always a heap address.
2170 if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2171 return Type::OopPtr;
2172 }
2173 // Offset is small => always a heap address.
2174 const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2175 if (offset_type != nullptr &&
2176 base_type->offset() == 0 && // (should always be?)
2177 offset_type->_lo >= 0 &&
2178 !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2179 return Type::OopPtr;
2180 } else if (type == T_OBJECT) {
2181 // off heap access to an oop doesn't make any sense. Has to be on
2182 // heap.
2183 return Type::OopPtr;
2184 }
2185 // Otherwise, it might either be oop+off or null+addr.
2186 return Type::AnyPtr;
2187 } else {
2188 // No information:
2189 return Type::AnyPtr;
2190 }
2191 }
2192
2193 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2194 Node* uncasted_base = base;
2195 int kind = classify_unsafe_addr(uncasted_base, offset, type);
2196 if (kind == Type::RawPtr) {
2197 return basic_plus_adr(top(), uncasted_base, offset);
2198 } else if (kind == Type::AnyPtr) {
2199 assert(base == uncasted_base, "unexpected base change");
2200 if (can_cast) {
2201 if (!_gvn.type(base)->speculative_maybe_null() &&
2202 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2203 // According to profiling, this access is always on
2204 // heap. Casting the base to not null and thus avoiding membars
2205 // around the access should allow better optimizations
2206 Node* null_ctl = top();
2207 base = null_check_oop(base, &null_ctl, true, true, true);
2208 assert(null_ctl->is_top(), "no null control here");
2209 return basic_plus_adr(base, offset);
2210 } else if (_gvn.type(base)->speculative_always_null() &&
2211 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2212 // According to profiling, this access is always off
2213 // heap.
2214 base = null_assert(base);
2215 Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2216 offset = MakeConX(0);
2217 return basic_plus_adr(top(), raw_base, offset);
2218 }
2219 }
2220 // We don't know if it's an on heap or off heap access. Fall back
2221 // to raw memory access.
2222 Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2223 return basic_plus_adr(top(), raw, offset);
2224 } else {
2225 assert(base == uncasted_base, "unexpected base change");
2226 // We know it's an on heap access so base can't be null
2227 if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2228 base = must_be_not_null(base, true);
2229 }
2230 return basic_plus_adr(base, offset);
2231 }
2232 }
2233
2234 //--------------------------inline_number_methods-----------------------------
2235 // inline int Integer.numberOfLeadingZeros(int)
2236 // inline int Long.numberOfLeadingZeros(long)
2237 //
2238 // inline int Integer.numberOfTrailingZeros(int)
2239 // inline int Long.numberOfTrailingZeros(long)
2240 //
2241 // inline int Integer.bitCount(int)
2242 // inline int Long.bitCount(long)
2243 //
2244 // inline char Character.reverseBytes(char)
2245 // inline short Short.reverseBytes(short)
2246 // inline int Integer.reverseBytes(int)
2247 // inline long Long.reverseBytes(long)
2248 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2249 Node* arg = argument(0);
2250 Node* n = nullptr;
2251 switch (id) {
2252 case vmIntrinsics::_numberOfLeadingZeros_i: n = new CountLeadingZerosINode( arg); break;
2253 case vmIntrinsics::_numberOfLeadingZeros_l: n = new CountLeadingZerosLNode( arg); break;
2254 case vmIntrinsics::_numberOfTrailingZeros_i: n = new CountTrailingZerosINode(arg); break;
2255 case vmIntrinsics::_numberOfTrailingZeros_l: n = new CountTrailingZerosLNode(arg); break;
2256 case vmIntrinsics::_bitCount_i: n = new PopCountINode( arg); break;
2257 case vmIntrinsics::_bitCount_l: n = new PopCountLNode( arg); break;
2258 case vmIntrinsics::_reverseBytes_c: n = new ReverseBytesUSNode( arg); break;
2259 case vmIntrinsics::_reverseBytes_s: n = new ReverseBytesSNode( arg); break;
2260 case vmIntrinsics::_reverseBytes_i: n = new ReverseBytesINode( arg); break;
2261 case vmIntrinsics::_reverseBytes_l: n = new ReverseBytesLNode( arg); break;
2262 case vmIntrinsics::_reverse_i: n = new ReverseINode( arg); break;
2263 case vmIntrinsics::_reverse_l: n = new ReverseLNode( arg); break;
2264 default: fatal_unexpected_iid(id); break;
2265 }
2266 set_result(_gvn.transform(n));
2267 return true;
2268 }
2269
2270 //--------------------------inline_bitshuffle_methods-----------------------------
2271 // inline int Integer.compress(int, int)
2272 // inline int Integer.expand(int, int)
2273 // inline long Long.compress(long, long)
2274 // inline long Long.expand(long, long)
2275 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2276 Node* n = nullptr;
2277 switch (id) {
2278 case vmIntrinsics::_compress_i: n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2279 case vmIntrinsics::_expand_i: n = new ExpandBitsNode(argument(0), argument(1), TypeInt::INT); break;
2280 case vmIntrinsics::_compress_l: n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2281 case vmIntrinsics::_expand_l: n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2282 default: fatal_unexpected_iid(id); break;
2283 }
2284 set_result(_gvn.transform(n));
2285 return true;
2286 }
2287
2288 //--------------------------inline_number_methods-----------------------------
2289 // inline int Integer.compareUnsigned(int, int)
2290 // inline int Long.compareUnsigned(long, long)
2291 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2292 Node* arg1 = argument(0);
2293 Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2294 Node* n = nullptr;
2295 switch (id) {
2296 case vmIntrinsics::_compareUnsigned_i: n = new CmpU3Node(arg1, arg2); break;
2297 case vmIntrinsics::_compareUnsigned_l: n = new CmpUL3Node(arg1, arg2); break;
2298 default: fatal_unexpected_iid(id); break;
2299 }
2300 set_result(_gvn.transform(n));
2301 return true;
2302 }
2303
2304 //--------------------------inline_unsigned_divmod_methods-----------------------------
2305 // inline int Integer.divideUnsigned(int, int)
2306 // inline int Integer.remainderUnsigned(int, int)
2307 // inline long Long.divideUnsigned(long, long)
2308 // inline long Long.remainderUnsigned(long, long)
2309 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2310 Node* n = nullptr;
2311 switch (id) {
2312 case vmIntrinsics::_divideUnsigned_i: {
2313 zero_check_int(argument(1));
2314 // Compile-time detect of null-exception
2315 if (stopped()) {
2316 return true; // keep the graph constructed so far
2317 }
2318 n = new UDivINode(control(), argument(0), argument(1));
2319 break;
2320 }
2321 case vmIntrinsics::_divideUnsigned_l: {
2322 zero_check_long(argument(2));
2323 // Compile-time detect of null-exception
2324 if (stopped()) {
2325 return true; // keep the graph constructed so far
2326 }
2327 n = new UDivLNode(control(), argument(0), argument(2));
2328 break;
2329 }
2330 case vmIntrinsics::_remainderUnsigned_i: {
2331 zero_check_int(argument(1));
2332 // Compile-time detect of null-exception
2333 if (stopped()) {
2334 return true; // keep the graph constructed so far
2335 }
2336 n = new UModINode(control(), argument(0), argument(1));
2337 break;
2338 }
2339 case vmIntrinsics::_remainderUnsigned_l: {
2340 zero_check_long(argument(2));
2341 // Compile-time detect of null-exception
2342 if (stopped()) {
2343 return true; // keep the graph constructed so far
2344 }
2345 n = new UModLNode(control(), argument(0), argument(2));
2346 break;
2347 }
2348 default: fatal_unexpected_iid(id); break;
2349 }
2350 set_result(_gvn.transform(n));
2351 return true;
2352 }
2353
2354 //----------------------------inline_unsafe_access----------------------------
2355
2356 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2357 // Attempt to infer a sharper value type from the offset and base type.
2358 ciKlass* sharpened_klass = nullptr;
2359 bool null_free = false;
2360
2361 // See if it is an instance field, with an object type.
2362 if (alias_type->field() != nullptr) {
2363 if (alias_type->field()->type()->is_klass()) {
2364 sharpened_klass = alias_type->field()->type()->as_klass();
2365 null_free = alias_type->field()->is_null_free();
2366 }
2367 }
2368
2369 const TypeOopPtr* result = nullptr;
2370 // See if it is a narrow oop array.
2371 if (adr_type->isa_aryptr()) {
2372 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2373 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2374 null_free = adr_type->is_aryptr()->is_null_free();
2375 if (elem_type != nullptr && elem_type->is_loaded()) {
2376 // Sharpen the value type.
2377 result = elem_type;
2378 }
2379 }
2380 }
2381
2382 // The sharpened class might be unloaded if there is no class loader
2383 // contraint in place.
2384 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2385 // Sharpen the value type.
2386 result = TypeOopPtr::make_from_klass(sharpened_klass);
2387 if (null_free) {
2388 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2389 }
2390 }
2391 if (result != nullptr) {
2392 #ifndef PRODUCT
2393 if (C->print_intrinsics() || C->print_inlining()) {
2394 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2395 tty->print(" sharpened value: "); result->dump(); tty->cr();
2396 }
2397 #endif
2398 }
2399 return result;
2400 }
2401
2402 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2403 switch (kind) {
2404 case Relaxed:
2405 return MO_UNORDERED;
2406 case Opaque:
2407 return MO_RELAXED;
2408 case Acquire:
2409 return MO_ACQUIRE;
2410 case Release:
2411 return MO_RELEASE;
2412 case Volatile:
2413 return MO_SEQ_CST;
2414 default:
2415 ShouldNotReachHere();
2416 return 0;
2417 }
2418 }
2419
2420 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2421 _kit(kit),
2422 _sp(kit->sp()),
2423 _jvms(kit->jvms()),
2424 _map(kit->clone_map()),
2425 _discarded(false)
2426 {
2427 for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2428 Node* out = kit->control()->fast_out(i);
2429 if (out->is_CFG()) {
2430 _ctrl_succ.push(out);
2431 }
2432 }
2433 }
2434
2435 LibraryCallKit::SavedState::~SavedState() {
2436 if (_discarded) {
2437 _kit->destruct_map_clone(_map);
2438 return;
2439 }
2440 _kit->jvms()->set_map(_map);
2441 _kit->jvms()->set_sp(_sp);
2442 _map->set_jvms(_kit->jvms());
2443 _kit->set_map(_map);
2444 _kit->set_sp(_sp);
2445 for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2446 Node* out = _kit->control()->fast_out(i);
2447 if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2448 _kit->_gvn.hash_delete(out);
2449 out->set_req(0, _kit->C->top());
2450 _kit->C->record_for_igvn(out);
2451 --i; --imax;
2452 _kit->_gvn.hash_find_insert(out);
2453 }
2454 }
2455 }
2456
2457 void LibraryCallKit::SavedState::discard() {
2458 _discarded = true;
2459 }
2460
2461 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2462 if (callee()->is_static()) return false; // caller must have the capability!
2463 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2464 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2465 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2466 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2467
2468 if (is_reference_type(type)) {
2469 decorators |= ON_UNKNOWN_OOP_REF;
2470 }
2471
2472 if (unaligned) {
2473 decorators |= C2_UNALIGNED;
2474 }
2475
2476 #ifndef PRODUCT
2477 {
2478 ResourceMark rm;
2479 // Check the signatures.
2480 ciSignature* sig = callee()->signature();
2481 #ifdef ASSERT
2482 if (!is_store) {
2483 // Object getReference(Object base, int/long offset), etc.
2484 BasicType rtype = sig->return_type()->basic_type();
2485 assert(rtype == type, "getter must return the expected value");
2486 assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2487 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2488 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2489 } else {
2490 // void putReference(Object base, int/long offset, Object x), etc.
2491 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2492 assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2493 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2494 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2495 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2496 assert(vtype == type, "putter must accept the expected value");
2497 }
2498 #endif // ASSERT
2499 }
2500 #endif //PRODUCT
2501
2502 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2503
2504 Node* receiver = argument(0); // type: oop
2505
2506 // Build address expression.
2507 Node* heap_base_oop = top();
2508
2509 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2510 Node* base = argument(1); // type: oop
2511 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2512 Node* offset = argument(2); // type: long
2513 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2514 // to be plain byte offsets, which are also the same as those accepted
2515 // by oopDesc::field_addr.
2516 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2517 "fieldOffset must be byte-scaled");
2518
2519 ciInlineKlass* inline_klass = nullptr;
2520 if (is_flat) {
2521 const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2522 if (cls == nullptr || cls->const_oop() == nullptr) {
2523 return false;
2524 }
2525 ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2526 if (!mirror_type->is_inlinetype()) {
2527 return false;
2528 }
2529 inline_klass = mirror_type->as_inline_klass();
2530 }
2531
2532 if (base->is_InlineType()) {
2533 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2534 InlineTypeNode* vt = base->as_InlineType();
2535 if (offset->is_Con()) {
2536 long off = find_long_con(offset, 0);
2537 ciInlineKlass* vk = vt->type()->inline_klass();
2538 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2539 return false;
2540 }
2541
2542 ciField* field = vk->get_non_flat_field_by_offset(off);
2543 if (field != nullptr) {
2544 BasicType bt = type2field[field->type()->basic_type()];
2545 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2546 bt = T_OBJECT;
2547 }
2548 if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2549 Node* value = vt->field_value_by_offset(off, false);
2550 if (value->is_InlineType()) {
2551 value = value->as_InlineType()->adjust_scalarization_depth(this);
2552 }
2553 set_result(value);
2554 return true;
2555 }
2556 }
2557 }
2558 {
2559 // Re-execute the unsafe access if allocation triggers deoptimization.
2560 PreserveReexecuteState preexecs(this);
2561 jvms()->set_should_reexecute(true);
2562 vt = vt->buffer(this);
2563 }
2564 base = vt->get_oop();
2565 }
2566
2567 // 32-bit machines ignore the high half!
2568 offset = ConvL2X(offset);
2569
2570 // Save state and restore on bailout
2571 SavedState old_state(this);
2572
2573 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2574 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2575
2576 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2577 if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2578 decorators |= IN_NATIVE; // off-heap primitive access
2579 } else {
2580 return false; // off-heap oop accesses are not supported
2581 }
2582 } else {
2583 heap_base_oop = base; // on-heap or mixed access
2584 }
2585
2586 // Can base be null? Otherwise, always on-heap access.
2587 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2588
2589 if (!can_access_non_heap) {
2590 decorators |= IN_HEAP;
2591 }
2592
2593 Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2594
2595 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2596 if (adr_type == TypePtr::NULL_PTR) {
2597 return false; // off-heap access with zero address
2598 }
2599
2600 // Try to categorize the address.
2601 Compile::AliasType* alias_type = C->alias_type(adr_type);
2602 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2603
2604 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2605 alias_type->adr_type() == TypeAryPtr::RANGE) {
2606 return false; // not supported
2607 }
2608
2609 bool mismatched = false;
2610 BasicType bt = T_ILLEGAL;
2611 ciField* field = nullptr;
2612 if (adr_type->isa_instptr()) {
2613 const TypeInstPtr* instptr = adr_type->is_instptr();
2614 ciInstanceKlass* k = instptr->instance_klass();
2615 int off = instptr->offset();
2616 if (instptr->const_oop() != nullptr &&
2617 k == ciEnv::current()->Class_klass() &&
2618 instptr->offset() >= (k->size_helper() * wordSize)) {
2619 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2620 field = k->get_field_by_offset(off, true);
2621 } else {
2622 field = k->get_non_flat_field_by_offset(off);
2623 }
2624 if (field != nullptr) {
2625 bt = type2field[field->type()->basic_type()];
2626 }
2627 if (bt != alias_type->basic_type()) {
2628 // Type mismatch. Is it an access to a nested flat field?
2629 field = k->get_field_by_offset(off, false);
2630 if (field != nullptr) {
2631 bt = type2field[field->type()->basic_type()];
2632 }
2633 }
2634 assert(bt == alias_type->basic_type() || is_flat, "should match");
2635 } else {
2636 bt = alias_type->basic_type();
2637 }
2638
2639 if (bt != T_ILLEGAL) {
2640 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2641 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2642 // Alias type doesn't differentiate between byte[] and boolean[]).
2643 // Use address type to get the element type.
2644 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2645 }
2646 if (is_reference_type(bt, true)) {
2647 // accessing an array field with getReference is not a mismatch
2648 bt = T_OBJECT;
2649 }
2650 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2651 // Don't intrinsify mismatched object accesses
2652 return false;
2653 }
2654 mismatched = (bt != type);
2655 } else if (alias_type->adr_type()->isa_oopptr()) {
2656 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2657 }
2658
2659 if (is_flat) {
2660 if (adr_type->isa_instptr()) {
2661 if (field == nullptr || field->type() != inline_klass) {
2662 mismatched = true;
2663 }
2664 } else if (adr_type->isa_aryptr()) {
2665 const Type* elem = adr_type->is_aryptr()->elem();
2666 if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2667 mismatched = true;
2668 }
2669 } else {
2670 mismatched = true;
2671 }
2672 if (is_store) {
2673 const Type* val_t = _gvn.type(val);
2674 if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2675 return false;
2676 }
2677 }
2678 }
2679
2680 old_state.discard();
2681 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2682
2683 if (mismatched) {
2684 decorators |= C2_MISMATCHED;
2685 }
2686
2687 // First guess at the value type.
2688 const Type *value_type = Type::get_const_basic_type(type);
2689
2690 // Figure out the memory ordering.
2691 decorators |= mo_decorator_for_access_kind(kind);
2692
2693 if (!is_store) {
2694 if (type == T_OBJECT && !is_flat) {
2695 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2696 if (tjp != nullptr) {
2697 value_type = tjp;
2698 }
2699 }
2700 }
2701
2702 receiver = null_check(receiver);
2703 if (stopped()) {
2704 return true;
2705 }
2706 // Heap pointers get a null-check from the interpreter,
2707 // as a courtesy. However, this is not guaranteed by Unsafe,
2708 // and it is not possible to fully distinguish unintended nulls
2709 // from intended ones in this API.
2710
2711 if (!is_store) {
2712 Node* p = nullptr;
2713 // Try to constant fold a load from a constant field
2714
2715 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2716 // final or stable field
2717 p = make_constant_from_field(field, heap_base_oop);
2718 }
2719
2720 if (p == nullptr) { // Could not constant fold the load
2721 if (is_flat) {
2722 p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2723 } else {
2724 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2725 const TypeOopPtr* ptr = value_type->make_oopptr();
2726 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2727 // Load a non-flattened inline type from memory
2728 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2729 }
2730 }
2731 // Normalize the value returned by getBoolean in the following cases
2732 if (type == T_BOOLEAN &&
2733 (mismatched ||
2734 heap_base_oop == top() || // - heap_base_oop is null or
2735 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2736 // and the unsafe access is made to large offset
2737 // (i.e., larger than the maximum offset necessary for any
2738 // field access)
2739 ) {
2740 IdealKit ideal = IdealKit(this);
2741 #define __ ideal.
2742 IdealVariable normalized_result(ideal);
2743 __ declarations_done();
2744 __ set(normalized_result, p);
2745 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2746 __ set(normalized_result, ideal.ConI(1));
2747 ideal.end_if();
2748 final_sync(ideal);
2749 p = __ value(normalized_result);
2750 #undef __
2751 }
2752 }
2753 if (type == T_ADDRESS) {
2754 p = gvn().transform(new CastP2XNode(nullptr, p));
2755 p = ConvX2UL(p);
2756 }
2757 // The load node has the control of the preceding MemBarCPUOrder. All
2758 // following nodes will have the control of the MemBarCPUOrder inserted at
2759 // the end of this method. So, pushing the load onto the stack at a later
2760 // point is fine.
2761 set_result(p);
2762 } else {
2763 if (bt == T_ADDRESS) {
2764 // Repackage the long as a pointer.
2765 val = ConvL2X(val);
2766 val = gvn().transform(new CastX2PNode(val));
2767 }
2768 if (is_flat) {
2769 val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2770 } else {
2771 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2772 }
2773 }
2774
2775 return true;
2776 }
2777
2778 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2779 #ifdef ASSERT
2780 {
2781 ResourceMark rm;
2782 // Check the signatures.
2783 ciSignature* sig = callee()->signature();
2784 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2785 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2786 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2787 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2788 if (is_store) {
2789 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2790 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2791 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2792 } else {
2793 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2794 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2795 }
2796 }
2797 #endif // ASSERT
2798
2799 assert(kind == Relaxed, "Only plain accesses for now");
2800 if (callee()->is_static()) {
2801 // caller must have the capability!
2802 return false;
2803 }
2804 C->set_has_unsafe_access(true);
2805
2806 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2807 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2808 // parameter valueType is not a constant
2809 return false;
2810 }
2811 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2812 if (!mirror_type->is_inlinetype()) {
2813 // Dead code
2814 return false;
2815 }
2816 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2817
2818 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2819 if (layout_type == nullptr || !layout_type->is_con()) {
2820 // parameter layoutKind is not a constant
2821 return false;
2822 }
2823 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2824 layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2825 "invalid layoutKind %d", layout_type->get_con());
2826 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2827 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2828 layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2829 "unexpected layoutKind %d", layout_type->get_con());
2830
2831 null_check(argument(0));
2832 if (stopped()) {
2833 return true;
2834 }
2835
2836 Node* base = must_be_not_null(argument(1), true);
2837 Node* offset = argument(2);
2838 const Type* base_type = _gvn.type(base);
2839
2840 Node* ptr;
2841 bool immutable_memory = false;
2842 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2843 if (base_type->isa_instptr()) {
2844 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2845 if (offset_type == nullptr || !offset_type->is_con()) {
2846 // Offset into a non-array should be a constant
2847 decorators |= C2_MISMATCHED;
2848 } else {
2849 int offset_con = checked_cast<int>(offset_type->get_con());
2850 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2851 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2852 if (field == nullptr) {
2853 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2854 decorators |= C2_MISMATCHED;
2855 } else {
2856 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2857 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2858 immutable_memory = field->is_strict() && field->is_final();
2859
2860 if (base->is_InlineType()) {
2861 assert(!is_store, "Cannot store into a non-larval value object");
2862 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2863 return true;
2864 }
2865 }
2866 }
2867
2868 if (base->is_InlineType()) {
2869 assert(!is_store, "Cannot store into a non-larval value object");
2870 base = base->as_InlineType()->buffer(this, true);
2871 }
2872 ptr = basic_plus_adr(base, ConvL2X(offset));
2873 } else if (base_type->isa_aryptr()) {
2874 decorators |= IS_ARRAY;
2875 if (layout == LayoutKind::REFERENCE) {
2876 if (!base_type->is_aryptr()->is_not_flat()) {
2877 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2878 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2879 replace_in_map(base, new_base);
2880 base = new_base;
2881 }
2882 ptr = basic_plus_adr(base, ConvL2X(offset));
2883 } else {
2884 if (UseArrayFlattening) {
2885 // Flat array must have an exact type
2886 bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2887 bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2888 Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2889 replace_in_map(base, new_base);
2890 base = new_base;
2891 ptr = basic_plus_adr(base, ConvL2X(offset));
2892 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2893 if (ptr_type->field_offset().get() != 0) {
2894 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2895 }
2896 } else {
2897 uncommon_trap(Deoptimization::Reason_intrinsic,
2898 Deoptimization::Action_none);
2899 return true;
2900 }
2901 }
2902 } else {
2903 decorators |= C2_MISMATCHED;
2904 ptr = basic_plus_adr(base, ConvL2X(offset));
2905 }
2906
2907 if (is_store) {
2908 Node* value = argument(6);
2909 const Type* value_type = _gvn.type(value);
2910 if (!value_type->is_inlinetypeptr()) {
2911 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2912 Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2913 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2914 replace_in_map(value, new_value);
2915 value = new_value;
2916 }
2917
2918 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());
2919 if (layout == LayoutKind::REFERENCE) {
2920 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2921 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2922 } else {
2923 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2924 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2925 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2926 }
2927
2928 return true;
2929 } else {
2930 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2931 InlineTypeNode* result;
2932 if (layout == LayoutKind::REFERENCE) {
2933 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2934 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2935 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2936 } else {
2937 bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2938 bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2939 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2940 }
2941
2942 set_result(result);
2943 return true;
2944 }
2945 }
2946
2947 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2948 Node* receiver = argument(0);
2949 Node* value = argument(1);
2950
2951 const Type* type = gvn().type(value);
2952 if (!type->is_inlinetypeptr()) {
2953 C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2954 return false;
2955 }
2956
2957 null_check(receiver);
2958 if (stopped()) {
2959 return true;
2960 }
2961
2962 value = null_check(value);
2963 if (stopped()) {
2964 return true;
2965 }
2966
2967 ciInlineKlass* vk = type->inline_klass();
2968 Node* klass = makecon(TypeKlassPtr::make(vk));
2969 Node* obj = new_instance(klass);
2970 AllocateNode::Ideal_allocation(obj)->_larval = true;
2971
2972 assert(value->is_InlineType(), "must be an InlineTypeNode");
2973 Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2974 value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2975
2976 set_result(obj);
2977 return true;
2978 }
2979
2980 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2981 Node* receiver = argument(0);
2982 Node* buffer = argument(1);
2983
2984 const Type* type = gvn().type(buffer);
2985 if (!type->is_inlinetypeptr()) {
2986 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2987 return false;
2988 }
2989
2990 AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2991 if (alloc == nullptr) {
2992 C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2993 return false;
2994 }
2995
2996 null_check(receiver);
2997 if (stopped()) {
2998 return true;
2999 }
3000
3001 // Unset the larval bit in the object header
3002 Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
3003 Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
3004 access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
3005
3006 // We must ensure that the buffer is properly published
3007 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
3008 assert(!type->maybe_null(), "result of an allocation should not be null");
3009 set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
3010 return true;
3011 }
3012
3013 //----------------------------inline_unsafe_load_store----------------------------
3014 // This method serves a couple of different customers (depending on LoadStoreKind):
3015 //
3016 // LS_cmp_swap:
3017 //
3018 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
3019 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
3020 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
3021 //
3022 // LS_cmp_swap_weak:
3023 //
3024 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
3025 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
3026 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
3027 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
3028 //
3029 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
3030 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
3031 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
3032 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
3033 //
3034 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
3035 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
3036 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
3037 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
3038 //
3039 // LS_cmp_exchange:
3040 //
3041 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
3042 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
3043 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
3044 //
3045 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
3046 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
3047 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
3048 //
3049 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
3050 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
3051 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
3052 //
3053 // LS_get_add:
3054 //
3055 // int getAndAddInt( Object o, long offset, int delta)
3056 // long getAndAddLong(Object o, long offset, long delta)
3057 //
3058 // LS_get_set:
3059 //
3060 // int getAndSet(Object o, long offset, int newValue)
3061 // long getAndSet(Object o, long offset, long newValue)
3062 // Object getAndSet(Object o, long offset, Object newValue)
3063 //
3064 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3065 // This basic scheme here is the same as inline_unsafe_access, but
3066 // differs in enough details that combining them would make the code
3067 // overly confusing. (This is a true fact! I originally combined
3068 // them, but even I was confused by it!) As much code/comments as
3069 // possible are retained from inline_unsafe_access though to make
3070 // the correspondences clearer. - dl
3071
3072 if (callee()->is_static()) return false; // caller must have the capability!
3073
3074 DecoratorSet decorators = C2_UNSAFE_ACCESS;
3075 decorators |= mo_decorator_for_access_kind(access_kind);
3076
3077 #ifndef PRODUCT
3078 BasicType rtype;
3079 {
3080 ResourceMark rm;
3081 // Check the signatures.
3082 ciSignature* sig = callee()->signature();
3083 rtype = sig->return_type()->basic_type();
3084 switch(kind) {
3085 case LS_get_add:
3086 case LS_get_set: {
3087 // Check the signatures.
3088 #ifdef ASSERT
3089 assert(rtype == type, "get and set must return the expected type");
3090 assert(sig->count() == 3, "get and set has 3 arguments");
3091 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3092 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3093 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3094 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3095 #endif // ASSERT
3096 break;
3097 }
3098 case LS_cmp_swap:
3099 case LS_cmp_swap_weak: {
3100 // Check the signatures.
3101 #ifdef ASSERT
3102 assert(rtype == T_BOOLEAN, "CAS must return boolean");
3103 assert(sig->count() == 4, "CAS has 4 arguments");
3104 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3105 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3106 #endif // ASSERT
3107 break;
3108 }
3109 case LS_cmp_exchange: {
3110 // Check the signatures.
3111 #ifdef ASSERT
3112 assert(rtype == type, "CAS must return the expected type");
3113 assert(sig->count() == 4, "CAS has 4 arguments");
3114 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3115 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3116 #endif // ASSERT
3117 break;
3118 }
3119 default:
3120 ShouldNotReachHere();
3121 }
3122 }
3123 #endif //PRODUCT
3124
3125 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
3126
3127 // Get arguments:
3128 Node* receiver = nullptr;
3129 Node* base = nullptr;
3130 Node* offset = nullptr;
3131 Node* oldval = nullptr;
3132 Node* newval = nullptr;
3133 switch(kind) {
3134 case LS_cmp_swap:
3135 case LS_cmp_swap_weak:
3136 case LS_cmp_exchange: {
3137 const bool two_slot_type = type2size[type] == 2;
3138 receiver = argument(0); // type: oop
3139 base = argument(1); // type: oop
3140 offset = argument(2); // type: long
3141 oldval = argument(4); // type: oop, int, or long
3142 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
3143 break;
3144 }
3145 case LS_get_add:
3146 case LS_get_set: {
3147 receiver = argument(0); // type: oop
3148 base = argument(1); // type: oop
3149 offset = argument(2); // type: long
3150 oldval = nullptr;
3151 newval = argument(4); // type: oop, int, or long
3152 break;
3153 }
3154 default:
3155 ShouldNotReachHere();
3156 }
3157
3158 // Build field offset expression.
3159 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3160 // to be plain byte offsets, which are also the same as those accepted
3161 // by oopDesc::field_addr.
3162 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3163 // 32-bit machines ignore the high half of long offsets
3164 offset = ConvL2X(offset);
3165 // Save state and restore on bailout
3166 SavedState old_state(this);
3167 Node* adr = make_unsafe_address(base, offset,type, false);
3168 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3169
3170 Compile::AliasType* alias_type = C->alias_type(adr_type);
3171 BasicType bt = alias_type->basic_type();
3172 if (bt != T_ILLEGAL &&
3173 (is_reference_type(bt) != (type == T_OBJECT))) {
3174 // Don't intrinsify mismatched object accesses.
3175 return false;
3176 }
3177
3178 old_state.discard();
3179
3180 // For CAS, unlike inline_unsafe_access, there seems no point in
3181 // trying to refine types. Just use the coarse types here.
3182 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3183 const Type *value_type = Type::get_const_basic_type(type);
3184
3185 switch (kind) {
3186 case LS_get_set:
3187 case LS_cmp_exchange: {
3188 if (type == T_OBJECT) {
3189 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3190 if (tjp != nullptr) {
3191 value_type = tjp;
3192 }
3193 }
3194 break;
3195 }
3196 case LS_cmp_swap:
3197 case LS_cmp_swap_weak:
3198 case LS_get_add:
3199 break;
3200 default:
3201 ShouldNotReachHere();
3202 }
3203
3204 // Null check receiver.
3205 receiver = null_check(receiver);
3206 if (stopped()) {
3207 return true;
3208 }
3209
3210 int alias_idx = C->get_alias_index(adr_type);
3211
3212 if (is_reference_type(type)) {
3213 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3214
3215 if (oldval != nullptr && oldval->is_InlineType()) {
3216 // Re-execute the unsafe access if allocation triggers deoptimization.
3217 PreserveReexecuteState preexecs(this);
3218 jvms()->set_should_reexecute(true);
3219 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3220 }
3221 if (newval != nullptr && newval->is_InlineType()) {
3222 // Re-execute the unsafe access if allocation triggers deoptimization.
3223 PreserveReexecuteState preexecs(this);
3224 jvms()->set_should_reexecute(true);
3225 newval = newval->as_InlineType()->buffer(this)->get_oop();
3226 }
3227
3228 // Transformation of a value which could be null pointer (CastPP #null)
3229 // could be delayed during Parse (for example, in adjust_map_after_if()).
3230 // Execute transformation here to avoid barrier generation in such case.
3231 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3232 newval = _gvn.makecon(TypePtr::NULL_PTR);
3233
3234 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3235 // Refine the value to a null constant, when it is known to be null
3236 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3237 }
3238 }
3239
3240 Node* result = nullptr;
3241 switch (kind) {
3242 case LS_cmp_exchange: {
3243 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3244 oldval, newval, value_type, type, decorators);
3245 break;
3246 }
3247 case LS_cmp_swap_weak:
3248 decorators |= C2_WEAK_CMPXCHG;
3249 case LS_cmp_swap: {
3250 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3251 oldval, newval, value_type, type, decorators);
3252 break;
3253 }
3254 case LS_get_set: {
3255 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3256 newval, value_type, type, decorators);
3257 break;
3258 }
3259 case LS_get_add: {
3260 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3261 newval, value_type, type, decorators);
3262 break;
3263 }
3264 default:
3265 ShouldNotReachHere();
3266 }
3267
3268 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3269 set_result(result);
3270 return true;
3271 }
3272
3273 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3274 // Regardless of form, don't allow previous ld/st to move down,
3275 // then issue acquire, release, or volatile mem_bar.
3276 insert_mem_bar(Op_MemBarCPUOrder);
3277 switch(id) {
3278 case vmIntrinsics::_loadFence:
3279 insert_mem_bar(Op_LoadFence);
3280 return true;
3281 case vmIntrinsics::_storeFence:
3282 insert_mem_bar(Op_StoreFence);
3283 return true;
3284 case vmIntrinsics::_storeStoreFence:
3285 insert_mem_bar(Op_StoreStoreFence);
3286 return true;
3287 case vmIntrinsics::_fullFence:
3288 insert_mem_bar(Op_MemBarVolatile);
3289 return true;
3290 default:
3291 fatal_unexpected_iid(id);
3292 return false;
3293 }
3294 }
3295
3296 bool LibraryCallKit::inline_onspinwait() {
3297 insert_mem_bar(Op_OnSpinWait);
3298 return true;
3299 }
3300
3301 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3302 if (!kls->is_Con()) {
3303 return true;
3304 }
3305 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3306 if (klsptr == nullptr) {
3307 return true;
3308 }
3309 ciInstanceKlass* ik = klsptr->instance_klass();
3310 // don't need a guard for a klass that is already initialized
3311 return !ik->is_initialized();
3312 }
3313
3314 //----------------------------inline_unsafe_writeback0-------------------------
3315 // public native void Unsafe.writeback0(long address)
3316 bool LibraryCallKit::inline_unsafe_writeback0() {
3317 if (!Matcher::has_match_rule(Op_CacheWB)) {
3318 return false;
3319 }
3320 #ifndef PRODUCT
3321 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3322 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3323 ciSignature* sig = callee()->signature();
3324 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3325 #endif
3326 null_check_receiver(); // null-check, then ignore
3327 Node *addr = argument(1);
3328 addr = new CastX2PNode(addr);
3329 addr = _gvn.transform(addr);
3330 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3331 flush = _gvn.transform(flush);
3332 set_memory(flush, TypeRawPtr::BOTTOM);
3333 return true;
3334 }
3335
3336 //----------------------------inline_unsafe_writeback0-------------------------
3337 // public native void Unsafe.writeback0(long address)
3338 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3339 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3340 return false;
3341 }
3342 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3343 return false;
3344 }
3345 #ifndef PRODUCT
3346 assert(Matcher::has_match_rule(Op_CacheWB),
3347 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3348 : "found match rule for CacheWBPostSync but not CacheWB"));
3349
3350 #endif
3351 null_check_receiver(); // null-check, then ignore
3352 Node *sync;
3353 if (is_pre) {
3354 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3355 } else {
3356 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3357 }
3358 sync = _gvn.transform(sync);
3359 set_memory(sync, TypeRawPtr::BOTTOM);
3360 return true;
3361 }
3362
3363 //----------------------------inline_unsafe_allocate---------------------------
3364 // public native Object Unsafe.allocateInstance(Class<?> cls);
3365 bool LibraryCallKit::inline_unsafe_allocate() {
3366
3367 #if INCLUDE_JVMTI
3368 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3369 return false;
3370 }
3371 #endif //INCLUDE_JVMTI
3372
3373 if (callee()->is_static()) return false; // caller must have the capability!
3374
3375 null_check_receiver(); // null-check, then ignore
3376 Node* cls = null_check(argument(1));
3377 if (stopped()) return true;
3378
3379 Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3380 kls = null_check(kls);
3381 if (stopped()) return true; // argument was like int.class
3382
3383 #if INCLUDE_JVMTI
3384 // Don't try to access new allocated obj in the intrinsic.
3385 // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3386 // Deoptimize and allocate in interpreter instead.
3387 Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3388 Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3389 Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3390 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3391 {
3392 BuildCutout unless(this, tst, PROB_MAX);
3393 uncommon_trap(Deoptimization::Reason_intrinsic,
3394 Deoptimization::Action_make_not_entrant);
3395 }
3396 if (stopped()) {
3397 return true;
3398 }
3399 #endif //INCLUDE_JVMTI
3400
3401 Node* test = nullptr;
3402 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3403 // Note: The argument might still be an illegal value like
3404 // Serializable.class or Object[].class. The runtime will handle it.
3405 // But we must make an explicit check for initialization.
3406 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3407 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3408 // can generate code to load it as unsigned byte.
3409 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3410 Node* bits = intcon(InstanceKlass::fully_initialized);
3411 test = _gvn.transform(new SubINode(inst, bits));
3412 // The 'test' is non-zero if we need to take a slow path.
3413 }
3414 Node* obj = nullptr;
3415 const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3416 if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3417 obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3418 } else {
3419 obj = new_instance(kls, test);
3420 }
3421 set_result(obj);
3422 return true;
3423 }
3424
3425 //------------------------inline_native_time_funcs--------------
3426 // inline code for System.currentTimeMillis() and System.nanoTime()
3427 // these have the same type and signature
3428 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3429 const TypeFunc* tf = OptoRuntime::void_long_Type();
3430 const TypePtr* no_memory_effects = nullptr;
3431 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3432 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3433 #ifdef ASSERT
3434 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3435 assert(value_top == top(), "second value must be top");
3436 #endif
3437 set_result(value);
3438 return true;
3439 }
3440
3441
3442 #if INCLUDE_JVMTI
3443
3444 // When notifications are disabled then just update the VTMS transition bit and return.
3445 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3446 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3447 if (!DoJVMTIVirtualThreadTransitions) {
3448 return true;
3449 }
3450 Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3451 IdealKit ideal(this);
3452
3453 Node* ONE = ideal.ConI(1);
3454 Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3455 Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3456 Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3457
3458 ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3459 sync_kit(ideal);
3460 // if notifyJvmti enabled then make a call to the given SharedRuntime function
3461 const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3462 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3463 ideal.sync_kit(this);
3464 } ideal.else_(); {
3465 // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3466 Node* thread = ideal.thread();
3467 Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3468 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3469
3470 sync_kit(ideal);
3471 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3472 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3473
3474 ideal.sync_kit(this);
3475 } ideal.end_if();
3476 final_sync(ideal);
3477
3478 return true;
3479 }
3480
3481 // Always update the is_disable_suspend bit.
3482 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3483 if (!DoJVMTIVirtualThreadTransitions) {
3484 return true;
3485 }
3486 IdealKit ideal(this);
3487
3488 {
3489 // unconditionally update the is_disable_suspend bit in current JavaThread
3490 Node* thread = ideal.thread();
3491 Node* arg = _gvn.transform(argument(0)); // argument for notification
3492 Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3493 const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3494
3495 sync_kit(ideal);
3496 access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3497 ideal.sync_kit(this);
3498 }
3499 final_sync(ideal);
3500
3501 return true;
3502 }
3503
3504 #endif // INCLUDE_JVMTI
3505
3506 #ifdef JFR_HAVE_INTRINSICS
3507
3508 /**
3509 * if oop->klass != null
3510 * // normal class
3511 * epoch = _epoch_state ? 2 : 1
3512 * if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3513 * ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3514 * }
3515 * id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3516 * else
3517 * // primitive class
3518 * if oop->array_klass != null
3519 * id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3520 * else
3521 * id = LAST_TYPE_ID + 1 // void class path
3522 * if (!signaled)
3523 * signaled = true
3524 */
3525 bool LibraryCallKit::inline_native_classID() {
3526 Node* cls = argument(0);
3527
3528 IdealKit ideal(this);
3529 #define __ ideal.
3530 IdealVariable result(ideal); __ declarations_done();
3531 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3532 basic_plus_adr(cls, java_lang_Class::klass_offset()),
3533 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3534
3535
3536 __ if_then(kls, BoolTest::ne, null()); {
3537 Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3538 Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3539
3540 Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3541 Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3542 epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3543 Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3544 mask = _gvn.transform(new OrLNode(mask, epoch));
3545 Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3546
3547 float unlikely = PROB_UNLIKELY(0.999);
3548 __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3549 sync_kit(ideal);
3550 make_runtime_call(RC_LEAF,
3551 OptoRuntime::class_id_load_barrier_Type(),
3552 CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3553 "class id load barrier",
3554 TypePtr::BOTTOM,
3555 kls);
3556 ideal.sync_kit(this);
3557 } __ end_if();
3558
3559 ideal.set(result, _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3560 } __ else_(); {
3561 Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3562 basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3563 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3564 __ if_then(array_kls, BoolTest::ne, null()); {
3565 Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3566 Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3567 Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3568 ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3569 } __ else_(); {
3570 // void class case
3571 ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3572 } __ end_if();
3573
3574 Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3575 Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3576 __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3577 ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3578 } __ end_if();
3579 } __ end_if();
3580
3581 final_sync(ideal);
3582 set_result(ideal.value(result));
3583 #undef __
3584 return true;
3585 }
3586
3587 //------------------------inline_native_jvm_commit------------------
3588 bool LibraryCallKit::inline_native_jvm_commit() {
3589 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3590
3591 // Save input memory and i_o state.
3592 Node* input_memory_state = reset_memory();
3593 set_all_memory(input_memory_state);
3594 Node* input_io_state = i_o();
3595
3596 // TLS.
3597 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3598 // Jfr java buffer.
3599 Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3600 Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3601 Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3602
3603 // Load the current value of the notified field in the JfrThreadLocal.
3604 Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3605 Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3606
3607 // Test for notification.
3608 Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3609 Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3610 IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3611
3612 // True branch, is notified.
3613 Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3614 set_control(is_notified);
3615
3616 // Reset notified state.
3617 store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3618 Node* notified_reset_memory = reset_memory();
3619
3620 // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3621 Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3622 // Convert the machine-word to a long.
3623 Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3624
3625 // False branch, not notified.
3626 Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3627 set_control(not_notified);
3628 set_all_memory(input_memory_state);
3629
3630 // Arg is the next position as a long.
3631 Node* arg = argument(0);
3632 // Convert long to machine-word.
3633 Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3634
3635 // Store the next_position to the underlying jfr java buffer.
3636 store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3637
3638 Node* commit_memory = reset_memory();
3639 set_all_memory(commit_memory);
3640
3641 // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3642 Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3643 Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3644 Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3645
3646 // And flags with lease constant.
3647 Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3648
3649 // Branch on lease to conditionalize returning the leased java buffer.
3650 Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3651 Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3652 IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3653
3654 // False branch, not a lease.
3655 Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3656
3657 // True branch, is lease.
3658 Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3659 set_control(is_lease);
3660
3661 // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3662 Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3663 OptoRuntime::void_void_Type(),
3664 SharedRuntime::jfr_return_lease(),
3665 "return_lease", TypePtr::BOTTOM);
3666 Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3667
3668 RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3669 record_for_igvn(lease_compare_rgn);
3670 PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3671 record_for_igvn(lease_compare_mem);
3672 PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3673 record_for_igvn(lease_compare_io);
3674 PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3675 record_for_igvn(lease_result_value);
3676
3677 // Update control and phi nodes.
3678 lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3679 lease_compare_rgn->init_req(_false_path, not_lease);
3680
3681 lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3682 lease_compare_mem->init_req(_false_path, commit_memory);
3683
3684 lease_compare_io->init_req(_true_path, i_o());
3685 lease_compare_io->init_req(_false_path, input_io_state);
3686
3687 lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3688 lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3689
3690 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3691 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3692 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3693 PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3694
3695 // Update control and phi nodes.
3696 result_rgn->init_req(_true_path, is_notified);
3697 result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3698
3699 result_mem->init_req(_true_path, notified_reset_memory);
3700 result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3701
3702 result_io->init_req(_true_path, input_io_state);
3703 result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3704
3705 result_value->init_req(_true_path, current_pos);
3706 result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3707
3708 // Set output state.
3709 set_control(_gvn.transform(result_rgn));
3710 set_all_memory(_gvn.transform(result_mem));
3711 set_i_o(_gvn.transform(result_io));
3712 set_result(result_rgn, result_value);
3713 return true;
3714 }
3715
3716 /*
3717 * The intrinsic is a model of this pseudo-code:
3718 *
3719 * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3720 * jobject h_event_writer = tl->java_event_writer();
3721 * if (h_event_writer == nullptr) {
3722 * return nullptr;
3723 * }
3724 * oop threadObj = Thread::threadObj();
3725 * oop vthread = java_lang_Thread::vthread(threadObj);
3726 * traceid tid;
3727 * bool pinVirtualThread;
3728 * bool excluded;
3729 * if (vthread != threadObj) { // i.e. current thread is virtual
3730 * tid = java_lang_Thread::tid(vthread);
3731 * u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3732 * pinVirtualThread = VMContinuations;
3733 * excluded = vthread_epoch_raw & excluded_mask;
3734 * if (!excluded) {
3735 * traceid current_epoch = JfrTraceIdEpoch::current_generation();
3736 * u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3737 * if (vthread_epoch != current_epoch) {
3738 * write_checkpoint();
3739 * }
3740 * }
3741 * } else {
3742 * tid = java_lang_Thread::tid(threadObj);
3743 * u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3744 * pinVirtualThread = false;
3745 * excluded = thread_epoch_raw & excluded_mask;
3746 * }
3747 * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3748 * traceid tid_in_event_writer = getField(event_writer, "threadID");
3749 * if (tid_in_event_writer != tid) {
3750 * setField(event_writer, "pinVirtualThread", pinVirtualThread);
3751 * setField(event_writer, "excluded", excluded);
3752 * setField(event_writer, "threadID", tid);
3753 * }
3754 * return event_writer
3755 */
3756 bool LibraryCallKit::inline_native_getEventWriter() {
3757 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3758
3759 // Save input memory and i_o state.
3760 Node* input_memory_state = reset_memory();
3761 set_all_memory(input_memory_state);
3762 Node* input_io_state = i_o();
3763
3764 // The most significant bit of the u2 is used to denote thread exclusion
3765 Node* excluded_shift = _gvn.intcon(15);
3766 Node* excluded_mask = _gvn.intcon(1 << 15);
3767 // The epoch generation is the range [1-32767]
3768 Node* epoch_mask = _gvn.intcon(32767);
3769
3770 // TLS
3771 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3772
3773 // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3774 Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3775
3776 // Load the eventwriter jobject handle.
3777 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3778
3779 // Null check the jobject handle.
3780 Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3781 Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3782 IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3783
3784 // False path, jobj is null.
3785 Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3786
3787 // True path, jobj is not null.
3788 Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3789
3790 set_control(jobj_is_not_null);
3791
3792 // Load the threadObj for the CarrierThread.
3793 Node* threadObj = generate_current_thread(tls_ptr);
3794
3795 // Load the vthread.
3796 Node* vthread = generate_virtual_thread(tls_ptr);
3797
3798 // If vthread != threadObj, this is a virtual thread.
3799 Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3800 Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3801 IfNode* iff_vthread_not_equal_threadObj =
3802 create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3803
3804 // False branch, fallback to threadObj.
3805 Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3806 set_control(vthread_equal_threadObj);
3807
3808 // Load the tid field from the vthread object.
3809 Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3810
3811 // Load the raw epoch value from the threadObj.
3812 Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3813 Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3814 _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3815 TypeInt::CHAR, T_CHAR,
3816 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3817
3818 // Mask off the excluded information from the epoch.
3819 Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3820
3821 // True branch, this is a virtual thread.
3822 Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3823 set_control(vthread_not_equal_threadObj);
3824
3825 // Load the tid field from the vthread object.
3826 Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3827
3828 // Continuation support determines if a virtual thread should be pinned.
3829 Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3830 Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3831
3832 // Load the raw epoch value from the vthread.
3833 Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3834 Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3835 TypeInt::CHAR, T_CHAR,
3836 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3837
3838 // Mask off the excluded information from the epoch.
3839 Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3840
3841 // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3842 Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3843 Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3844 IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3845
3846 // False branch, vthread is excluded, no need to write epoch info.
3847 Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3848
3849 // True branch, vthread is included, update epoch info.
3850 Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3851 set_control(included);
3852
3853 // Get epoch value.
3854 Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3855
3856 // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3857 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3858 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3859
3860 // Compare the epoch in the vthread to the current epoch generation.
3861 Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3862 Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3863 IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3864
3865 // False path, epoch is equal, checkpoint information is valid.
3866 Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3867
3868 // True path, epoch is not equal, write a checkpoint for the vthread.
3869 Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3870
3871 set_control(epoch_is_not_equal);
3872
3873 // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3874 // The call also updates the native thread local thread id and the vthread with the current epoch.
3875 Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3876 OptoRuntime::jfr_write_checkpoint_Type(),
3877 SharedRuntime::jfr_write_checkpoint(),
3878 "write_checkpoint", TypePtr::BOTTOM);
3879 Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3880
3881 // vthread epoch != current epoch
3882 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3883 record_for_igvn(epoch_compare_rgn);
3884 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3885 record_for_igvn(epoch_compare_mem);
3886 PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3887 record_for_igvn(epoch_compare_io);
3888
3889 // Update control and phi nodes.
3890 epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3891 epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3892 epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3893 epoch_compare_mem->init_req(_false_path, input_memory_state);
3894 epoch_compare_io->init_req(_true_path, i_o());
3895 epoch_compare_io->init_req(_false_path, input_io_state);
3896
3897 // excluded != true
3898 RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3899 record_for_igvn(exclude_compare_rgn);
3900 PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3901 record_for_igvn(exclude_compare_mem);
3902 PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3903 record_for_igvn(exclude_compare_io);
3904
3905 // Update control and phi nodes.
3906 exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3907 exclude_compare_rgn->init_req(_false_path, excluded);
3908 exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3909 exclude_compare_mem->init_req(_false_path, input_memory_state);
3910 exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3911 exclude_compare_io->init_req(_false_path, input_io_state);
3912
3913 // vthread != threadObj
3914 RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3915 record_for_igvn(vthread_compare_rgn);
3916 PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3917 PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3918 record_for_igvn(vthread_compare_io);
3919 PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3920 record_for_igvn(tid);
3921 PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3922 record_for_igvn(exclusion);
3923 PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3924 record_for_igvn(pinVirtualThread);
3925
3926 // Update control and phi nodes.
3927 vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3928 vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3929 vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3930 vthread_compare_mem->init_req(_false_path, input_memory_state);
3931 vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3932 vthread_compare_io->init_req(_false_path, input_io_state);
3933 tid->init_req(_true_path, _gvn.transform(vthread_tid));
3934 tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3935 exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3936 exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3937 pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3938 pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3939
3940 // Update branch state.
3941 set_control(_gvn.transform(vthread_compare_rgn));
3942 set_all_memory(_gvn.transform(vthread_compare_mem));
3943 set_i_o(_gvn.transform(vthread_compare_io));
3944
3945 // Load the event writer oop by dereferencing the jobject handle.
3946 ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3947 assert(klass_EventWriter->is_loaded(), "invariant");
3948 ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3949 const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3950 const TypeOopPtr* const xtype = aklass->as_instance_type();
3951 Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3952 Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3953
3954 // Load the current thread id from the event writer object.
3955 Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3956 // Get the field offset to, conditionally, store an updated tid value later.
3957 Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3958 // Get the field offset to, conditionally, store an updated exclusion value later.
3959 Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3960 // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3961 Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3962
3963 RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3964 record_for_igvn(event_writer_tid_compare_rgn);
3965 PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3966 record_for_igvn(event_writer_tid_compare_mem);
3967 PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3968 record_for_igvn(event_writer_tid_compare_io);
3969
3970 // Compare the current tid from the thread object to what is currently stored in the event writer object.
3971 Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3972 Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3973 IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3974
3975 // False path, tids are the same.
3976 Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3977
3978 // True path, tid is not equal, need to update the tid in the event writer.
3979 Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3980 record_for_igvn(tid_is_not_equal);
3981
3982 // Store the pin state to the event writer.
3983 store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3984
3985 // Store the exclusion state to the event writer.
3986 Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3987 store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3988
3989 // Store the tid to the event writer.
3990 store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3991
3992 // Update control and phi nodes.
3993 event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3994 event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3995 event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3996 event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3997 event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
3998 event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3999
4000 // Result of top level CFG, Memory, IO and Value.
4001 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4002 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4003 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4004 PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4005
4006 // Result control.
4007 result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4008 result_rgn->init_req(_false_path, jobj_is_null);
4009
4010 // Result memory.
4011 result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4012 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4013
4014 // Result IO.
4015 result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4016 result_io->init_req(_false_path, _gvn.transform(input_io_state));
4017
4018 // Result value.
4019 result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4020 result_value->init_req(_false_path, null()); // return null
4021
4022 // Set output state.
4023 set_control(_gvn.transform(result_rgn));
4024 set_all_memory(_gvn.transform(result_mem));
4025 set_i_o(_gvn.transform(result_io));
4026 set_result(result_rgn, result_value);
4027 return true;
4028 }
4029
4030 /*
4031 * The intrinsic is a model of this pseudo-code:
4032 *
4033 * JfrThreadLocal* const tl = thread->jfr_thread_local();
4034 * if (carrierThread != thread) { // is virtual thread
4035 * const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4036 * bool excluded = vthread_epoch_raw & excluded_mask;
4037 * AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4038 * AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4039 * if (!excluded) {
4040 * const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4041 * AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4042 * }
4043 * AtomicAccess::release_store(&tl->_vthread, true);
4044 * return;
4045 * }
4046 * AtomicAccess::release_store(&tl->_vthread, false);
4047 */
4048 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4049 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4050
4051 Node* input_memory_state = reset_memory();
4052 set_all_memory(input_memory_state);
4053
4054 // The most significant bit of the u2 is used to denote thread exclusion
4055 Node* excluded_mask = _gvn.intcon(1 << 15);
4056 // The epoch generation is the range [1-32767]
4057 Node* epoch_mask = _gvn.intcon(32767);
4058
4059 Node* const carrierThread = generate_current_thread(jt);
4060 // If thread != carrierThread, this is a virtual thread.
4061 Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4062 Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4063 IfNode* iff_thread_not_equal_carrierThread =
4064 create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4065
4066 Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4067
4068 // False branch, is carrierThread.
4069 Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4070 // Store release
4071 Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4072
4073 set_all_memory(input_memory_state);
4074
4075 // True branch, is virtual thread.
4076 Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4077 set_control(thread_not_equal_carrierThread);
4078
4079 // Load the raw epoch value from the vthread.
4080 Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4081 Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4082 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4083
4084 // Mask off the excluded information from the epoch.
4085 Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4086
4087 // Load the tid field from the thread.
4088 Node* tid = load_field_from_object(thread, "tid", "J");
4089
4090 // Store the vthread tid to the jfr thread local.
4091 Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4092 Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4093
4094 // Branch is_excluded to conditionalize updating the epoch .
4095 Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4096 Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4097 IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4098
4099 // True branch, vthread is excluded, no need to write epoch info.
4100 Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4101 set_control(excluded);
4102 Node* vthread_is_excluded = _gvn.intcon(1);
4103
4104 // False branch, vthread is included, update epoch info.
4105 Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4106 set_control(included);
4107 Node* vthread_is_included = _gvn.intcon(0);
4108
4109 // Get epoch value.
4110 Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4111
4112 // Store the vthread epoch to the jfr thread local.
4113 Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4114 Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4115
4116 RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4117 record_for_igvn(excluded_rgn);
4118 PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4119 record_for_igvn(excluded_mem);
4120 PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4121 record_for_igvn(exclusion);
4122
4123 // Merge the excluded control and memory.
4124 excluded_rgn->init_req(_true_path, excluded);
4125 excluded_rgn->init_req(_false_path, included);
4126 excluded_mem->init_req(_true_path, tid_memory);
4127 excluded_mem->init_req(_false_path, included_memory);
4128 exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4129 exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4130
4131 // Set intermediate state.
4132 set_control(_gvn.transform(excluded_rgn));
4133 set_all_memory(excluded_mem);
4134
4135 // Store the vthread exclusion state to the jfr thread local.
4136 Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4137 store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4138
4139 // Store release
4140 Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4141
4142 RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4143 record_for_igvn(thread_compare_rgn);
4144 PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4145 record_for_igvn(thread_compare_mem);
4146 PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4147 record_for_igvn(vthread);
4148
4149 // Merge the thread_compare control and memory.
4150 thread_compare_rgn->init_req(_true_path, control());
4151 thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4152 thread_compare_mem->init_req(_true_path, vthread_true_memory);
4153 thread_compare_mem->init_req(_false_path, vthread_false_memory);
4154
4155 // Set output state.
4156 set_control(_gvn.transform(thread_compare_rgn));
4157 set_all_memory(_gvn.transform(thread_compare_mem));
4158 }
4159
4160 #endif // JFR_HAVE_INTRINSICS
4161
4162 //------------------------inline_native_currentCarrierThread------------------
4163 bool LibraryCallKit::inline_native_currentCarrierThread() {
4164 Node* junk = nullptr;
4165 set_result(generate_current_thread(junk));
4166 return true;
4167 }
4168
4169 //------------------------inline_native_currentThread------------------
4170 bool LibraryCallKit::inline_native_currentThread() {
4171 Node* junk = nullptr;
4172 set_result(generate_virtual_thread(junk));
4173 return true;
4174 }
4175
4176 //------------------------inline_native_setVthread------------------
4177 bool LibraryCallKit::inline_native_setCurrentThread() {
4178 assert(C->method()->changes_current_thread(),
4179 "method changes current Thread but is not annotated ChangesCurrentThread");
4180 Node* arr = argument(1);
4181 Node* thread = _gvn.transform(new ThreadLocalNode());
4182 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4183 Node* thread_obj_handle
4184 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4185 thread_obj_handle = _gvn.transform(thread_obj_handle);
4186 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4187 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4188
4189 // Change the _monitor_owner_id of the JavaThread
4190 Node* tid = load_field_from_object(arr, "tid", "J");
4191 Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4192 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4193
4194 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4195 return true;
4196 }
4197
4198 const Type* LibraryCallKit::scopedValueCache_type() {
4199 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4200 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4201 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4202
4203 // Because we create the scopedValue cache lazily we have to make the
4204 // type of the result BotPTR.
4205 bool xk = etype->klass_is_exact();
4206 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4207 return objects_type;
4208 }
4209
4210 Node* LibraryCallKit::scopedValueCache_helper() {
4211 Node* thread = _gvn.transform(new ThreadLocalNode());
4212 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4213 // We cannot use immutable_memory() because we might flip onto a
4214 // different carrier thread, at which point we'll need to use that
4215 // carrier thread's cache.
4216 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4217 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4218 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4219 }
4220
4221 //------------------------inline_native_scopedValueCache------------------
4222 bool LibraryCallKit::inline_native_scopedValueCache() {
4223 Node* cache_obj_handle = scopedValueCache_helper();
4224 const Type* objects_type = scopedValueCache_type();
4225 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4226
4227 return true;
4228 }
4229
4230 //------------------------inline_native_setScopedValueCache------------------
4231 bool LibraryCallKit::inline_native_setScopedValueCache() {
4232 Node* arr = argument(0);
4233 Node* cache_obj_handle = scopedValueCache_helper();
4234 const Type* objects_type = scopedValueCache_type();
4235
4236 const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4237 access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4238
4239 return true;
4240 }
4241
4242 //------------------------inline_native_Continuation_pin and unpin-----------
4243
4244 // Shared implementation routine for both pin and unpin.
4245 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4246 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4247
4248 // Save input memory.
4249 Node* input_memory_state = reset_memory();
4250 set_all_memory(input_memory_state);
4251
4252 // TLS
4253 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4254 Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4255 Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4256
4257 // Null check the last continuation object.
4258 Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4259 Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4260 IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4261
4262 // False path, last continuation is null.
4263 Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4264
4265 // True path, last continuation is not null.
4266 Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4267
4268 set_control(continuation_is_not_null);
4269
4270 // Load the pin count from the last continuation.
4271 Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4272 Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4273
4274 // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4275 Node* pin_count_rhs;
4276 if (unpin) {
4277 pin_count_rhs = _gvn.intcon(0);
4278 } else {
4279 pin_count_rhs = _gvn.intcon(UINT32_MAX);
4280 }
4281 Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4282 Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4283 IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4284
4285 // True branch, pin count over/underflow.
4286 Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4287 {
4288 // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4289 // which will throw IllegalStateException for pin count over/underflow.
4290 // No memory changed so far - we can use memory create by reset_memory()
4291 // at the beginning of this intrinsic. No need to call reset_memory() again.
4292 PreserveJVMState pjvms(this);
4293 set_control(pin_count_over_underflow);
4294 uncommon_trap(Deoptimization::Reason_intrinsic,
4295 Deoptimization::Action_none);
4296 assert(stopped(), "invariant");
4297 }
4298
4299 // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4300 Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4301 set_control(valid_pin_count);
4302
4303 Node* next_pin_count;
4304 if (unpin) {
4305 next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4306 } else {
4307 next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4308 }
4309
4310 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4311
4312 // Result of top level CFG and Memory.
4313 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4314 record_for_igvn(result_rgn);
4315 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4316 record_for_igvn(result_mem);
4317
4318 result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4319 result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4320 result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4321 result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4322
4323 // Set output state.
4324 set_control(_gvn.transform(result_rgn));
4325 set_all_memory(_gvn.transform(result_mem));
4326
4327 return true;
4328 }
4329
4330 //-----------------------load_klass_from_mirror_common-------------------------
4331 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4332 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4333 // and branch to the given path on the region.
4334 // If never_see_null, take an uncommon trap on null, so we can optimistically
4335 // compile for the non-null case.
4336 // If the region is null, force never_see_null = true.
4337 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4338 bool never_see_null,
4339 RegionNode* region,
4340 int null_path,
4341 int offset) {
4342 if (region == nullptr) never_see_null = true;
4343 Node* p = basic_plus_adr(mirror, offset);
4344 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4345 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4346 Node* null_ctl = top();
4347 kls = null_check_oop(kls, &null_ctl, never_see_null);
4348 if (region != nullptr) {
4349 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4350 region->init_req(null_path, null_ctl);
4351 } else {
4352 assert(null_ctl == top(), "no loose ends");
4353 }
4354 return kls;
4355 }
4356
4357 //--------------------(inline_native_Class_query helpers)---------------------
4358 // Use this for JVM_ACC_INTERFACE.
4359 // Fall through if (mods & mask) == bits, take the guard otherwise.
4360 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4361 ByteSize offset, const Type* type, BasicType bt) {
4362 // Branch around if the given klass has the given modifier bit set.
4363 // Like generate_guard, adds a new path onto the region.
4364 Node* modp = basic_plus_adr(kls, in_bytes(offset));
4365 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4366 Node* mask = intcon(modifier_mask);
4367 Node* bits = intcon(modifier_bits);
4368 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4369 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4370 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4371 return generate_fair_guard(bol, region);
4372 }
4373
4374 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4375 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4376 Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4377 }
4378
4379 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4380 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4381 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4382 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4383 }
4384
4385 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4386 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4387 }
4388
4389 //-------------------------inline_native_Class_query-------------------
4390 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4391 const Type* return_type = TypeInt::BOOL;
4392 Node* prim_return_value = top(); // what happens if it's a primitive class?
4393 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4394 bool expect_prim = false; // most of these guys expect to work on refs
4395
4396 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4397
4398 Node* mirror = argument(0);
4399 Node* obj = top();
4400
4401 switch (id) {
4402 case vmIntrinsics::_isInstance:
4403 // nothing is an instance of a primitive type
4404 prim_return_value = intcon(0);
4405 obj = argument(1);
4406 break;
4407 case vmIntrinsics::_isHidden:
4408 prim_return_value = intcon(0);
4409 break;
4410 case vmIntrinsics::_getSuperclass:
4411 prim_return_value = null();
4412 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4413 break;
4414 default:
4415 fatal_unexpected_iid(id);
4416 break;
4417 }
4418
4419 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4420 if (mirror_con == nullptr) return false; // cannot happen?
4421
4422 #ifndef PRODUCT
4423 if (C->print_intrinsics() || C->print_inlining()) {
4424 ciType* k = mirror_con->java_mirror_type();
4425 if (k) {
4426 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4427 k->print_name();
4428 tty->cr();
4429 }
4430 }
4431 #endif
4432
4433 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4434 RegionNode* region = new RegionNode(PATH_LIMIT);
4435 record_for_igvn(region);
4436 PhiNode* phi = new PhiNode(region, return_type);
4437
4438 // The mirror will never be null of Reflection.getClassAccessFlags, however
4439 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4440 // if it is. See bug 4774291.
4441
4442 // For Reflection.getClassAccessFlags(), the null check occurs in
4443 // the wrong place; see inline_unsafe_access(), above, for a similar
4444 // situation.
4445 mirror = null_check(mirror);
4446 // If mirror or obj is dead, only null-path is taken.
4447 if (stopped()) return true;
4448
4449 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
4450
4451 // Now load the mirror's klass metaobject, and null-check it.
4452 // Side-effects region with the control path if the klass is null.
4453 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4454 // If kls is null, we have a primitive mirror.
4455 phi->init_req(_prim_path, prim_return_value);
4456 if (stopped()) { set_result(region, phi); return true; }
4457 bool safe_for_replace = (region->in(_prim_path) == top());
4458
4459 Node* p; // handy temp
4460 Node* null_ctl;
4461
4462 // Now that we have the non-null klass, we can perform the real query.
4463 // For constant classes, the query will constant-fold in LoadNode::Value.
4464 Node* query_value = top();
4465 switch (id) {
4466 case vmIntrinsics::_isInstance:
4467 // nothing is an instance of a primitive type
4468 query_value = gen_instanceof(obj, kls, safe_for_replace);
4469 break;
4470
4471 case vmIntrinsics::_isHidden:
4472 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4473 if (generate_hidden_class_guard(kls, region) != nullptr)
4474 // A guard was added. If the guard is taken, it was an hidden class.
4475 phi->add_req(intcon(1));
4476 // If we fall through, it's a plain class.
4477 query_value = intcon(0);
4478 break;
4479
4480
4481 case vmIntrinsics::_getSuperclass:
4482 // The rules here are somewhat unfortunate, but we can still do better
4483 // with random logic than with a JNI call.
4484 // Interfaces store null or Object as _super, but must report null.
4485 // Arrays store an intermediate super as _super, but must report Object.
4486 // Other types can report the actual _super.
4487 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4488 if (generate_interface_guard(kls, region) != nullptr)
4489 // A guard was added. If the guard is taken, it was an interface.
4490 phi->add_req(null());
4491 if (generate_array_guard(kls, region) != nullptr)
4492 // A guard was added. If the guard is taken, it was an array.
4493 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4494 // If we fall through, it's a plain class. Get its _super.
4495 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4496 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4497 null_ctl = top();
4498 kls = null_check_oop(kls, &null_ctl);
4499 if (null_ctl != top()) {
4500 // If the guard is taken, Object.superClass is null (both klass and mirror).
4501 region->add_req(null_ctl);
4502 phi ->add_req(null());
4503 }
4504 if (!stopped()) {
4505 query_value = load_mirror_from_klass(kls);
4506 }
4507 break;
4508
4509 default:
4510 fatal_unexpected_iid(id);
4511 break;
4512 }
4513
4514 // Fall-through is the normal case of a query to a real class.
4515 phi->init_req(1, query_value);
4516 region->init_req(1, control());
4517
4518 C->set_has_split_ifs(true); // Has chance for split-if optimization
4519 set_result(region, phi);
4520 return true;
4521 }
4522
4523
4524 //-------------------------inline_Class_cast-------------------
4525 bool LibraryCallKit::inline_Class_cast() {
4526 Node* mirror = argument(0); // Class
4527 Node* obj = argument(1);
4528 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4529 if (mirror_con == nullptr) {
4530 return false; // dead path (mirror->is_top()).
4531 }
4532 if (obj == nullptr || obj->is_top()) {
4533 return false; // dead path
4534 }
4535 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4536
4537 // First, see if Class.cast() can be folded statically.
4538 // java_mirror_type() returns non-null for compile-time Class constants.
4539 ciType* tm = mirror_con->java_mirror_type();
4540 if (tm != nullptr && tm->is_klass() &&
4541 tp != nullptr) {
4542 if (!tp->is_loaded()) {
4543 // Don't use intrinsic when class is not loaded.
4544 return false;
4545 } else {
4546 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4547 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4548 if (static_res == Compile::SSC_always_true) {
4549 // isInstance() is true - fold the code.
4550 set_result(obj);
4551 return true;
4552 } else if (static_res == Compile::SSC_always_false) {
4553 // Don't use intrinsic, have to throw ClassCastException.
4554 // If the reference is null, the non-intrinsic bytecode will
4555 // be optimized appropriately.
4556 return false;
4557 }
4558 }
4559 }
4560
4561 // Bailout intrinsic and do normal inlining if exception path is frequent.
4562 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4563 return false;
4564 }
4565
4566 // Generate dynamic checks.
4567 // Class.cast() is java implementation of _checkcast bytecode.
4568 // Do checkcast (Parse::do_checkcast()) optimizations here.
4569
4570 mirror = null_check(mirror);
4571 // If mirror is dead, only null-path is taken.
4572 if (stopped()) {
4573 return true;
4574 }
4575
4576 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4577 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4578 RegionNode* region = new RegionNode(PATH_LIMIT);
4579 record_for_igvn(region);
4580
4581 // Now load the mirror's klass metaobject, and null-check it.
4582 // If kls is null, we have a primitive mirror and
4583 // nothing is an instance of a primitive type.
4584 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4585
4586 Node* res = top();
4587 Node* io = i_o();
4588 Node* mem = merged_memory();
4589 if (!stopped()) {
4590
4591 Node* bad_type_ctrl = top();
4592 // Do checkcast optimizations.
4593 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4594 region->init_req(_bad_type_path, bad_type_ctrl);
4595 }
4596 if (region->in(_prim_path) != top() ||
4597 region->in(_bad_type_path) != top() ||
4598 region->in(_npe_path) != top()) {
4599 // Let Interpreter throw ClassCastException.
4600 PreserveJVMState pjvms(this);
4601 set_control(_gvn.transform(region));
4602 // Set IO and memory because gen_checkcast may override them when buffering inline types
4603 set_i_o(io);
4604 set_all_memory(mem);
4605 uncommon_trap(Deoptimization::Reason_intrinsic,
4606 Deoptimization::Action_maybe_recompile);
4607 }
4608 if (!stopped()) {
4609 set_result(res);
4610 }
4611 return true;
4612 }
4613
4614
4615 //--------------------------inline_native_subtype_check------------------------
4616 // This intrinsic takes the JNI calls out of the heart of
4617 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4618 bool LibraryCallKit::inline_native_subtype_check() {
4619 // Pull both arguments off the stack.
4620 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4621 args[0] = argument(0);
4622 args[1] = argument(1);
4623 Node* klasses[2]; // corresponding Klasses: superk, subk
4624 klasses[0] = klasses[1] = top();
4625
4626 enum {
4627 // A full decision tree on {superc is prim, subc is prim}:
4628 _prim_0_path = 1, // {P,N} => false
4629 // {P,P} & superc!=subc => false
4630 _prim_same_path, // {P,P} & superc==subc => true
4631 _prim_1_path, // {N,P} => false
4632 _ref_subtype_path, // {N,N} & subtype check wins => true
4633 _both_ref_path, // {N,N} & subtype check loses => false
4634 PATH_LIMIT
4635 };
4636
4637 RegionNode* region = new RegionNode(PATH_LIMIT);
4638 RegionNode* prim_region = new RegionNode(2);
4639 Node* phi = new PhiNode(region, TypeInt::BOOL);
4640 record_for_igvn(region);
4641 record_for_igvn(prim_region);
4642
4643 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4644 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4645 int class_klass_offset = java_lang_Class::klass_offset();
4646
4647 // First null-check both mirrors and load each mirror's klass metaobject.
4648 int which_arg;
4649 for (which_arg = 0; which_arg <= 1; which_arg++) {
4650 Node* arg = args[which_arg];
4651 arg = null_check(arg);
4652 if (stopped()) break;
4653 args[which_arg] = arg;
4654
4655 Node* p = basic_plus_adr(arg, class_klass_offset);
4656 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4657 klasses[which_arg] = _gvn.transform(kls);
4658 }
4659
4660 // Having loaded both klasses, test each for null.
4661 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4662 for (which_arg = 0; which_arg <= 1; which_arg++) {
4663 Node* kls = klasses[which_arg];
4664 Node* null_ctl = top();
4665 kls = null_check_oop(kls, &null_ctl, never_see_null);
4666 if (which_arg == 0) {
4667 prim_region->init_req(1, null_ctl);
4668 } else {
4669 region->init_req(_prim_1_path, null_ctl);
4670 }
4671 if (stopped()) break;
4672 klasses[which_arg] = kls;
4673 }
4674
4675 if (!stopped()) {
4676 // now we have two reference types, in klasses[0..1]
4677 Node* subk = klasses[1]; // the argument to isAssignableFrom
4678 Node* superk = klasses[0]; // the receiver
4679 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4680 region->set_req(_ref_subtype_path, control());
4681 }
4682
4683 // If both operands are primitive (both klasses null), then
4684 // we must return true when they are identical primitives.
4685 // It is convenient to test this after the first null klass check.
4686 // This path is also used if superc is a value mirror.
4687 set_control(_gvn.transform(prim_region));
4688 if (!stopped()) {
4689 // Since superc is primitive, make a guard for the superc==subc case.
4690 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4691 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4692 generate_fair_guard(bol_eq, region);
4693 if (region->req() == PATH_LIMIT+1) {
4694 // A guard was added. If the added guard is taken, superc==subc.
4695 region->swap_edges(PATH_LIMIT, _prim_same_path);
4696 region->del_req(PATH_LIMIT);
4697 }
4698 region->set_req(_prim_0_path, control()); // Not equal after all.
4699 }
4700
4701 // these are the only paths that produce 'true':
4702 phi->set_req(_prim_same_path, intcon(1));
4703 phi->set_req(_ref_subtype_path, intcon(1));
4704
4705 // pull together the cases:
4706 assert(region->req() == PATH_LIMIT, "sane region");
4707 for (uint i = 1; i < region->req(); i++) {
4708 Node* ctl = region->in(i);
4709 if (ctl == nullptr || ctl == top()) {
4710 region->set_req(i, top());
4711 phi ->set_req(i, top());
4712 } else if (phi->in(i) == nullptr) {
4713 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4714 }
4715 }
4716
4717 set_control(_gvn.transform(region));
4718 set_result(_gvn.transform(phi));
4719 return true;
4720 }
4721
4722 //---------------------generate_array_guard_common------------------------
4723 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4724
4725 if (stopped()) {
4726 return nullptr;
4727 }
4728
4729 // Like generate_guard, adds a new path onto the region.
4730 jint layout_con = 0;
4731 Node* layout_val = get_layout_helper(kls, layout_con);
4732 if (layout_val == nullptr) {
4733 bool query = 0;
4734 switch(kind) {
4735 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4736 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4737 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4738 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4739 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4740 default:
4741 ShouldNotReachHere();
4742 }
4743 if (!query) {
4744 return nullptr; // never a branch
4745 } else { // always a branch
4746 Node* always_branch = control();
4747 if (region != nullptr)
4748 region->add_req(always_branch);
4749 set_control(top());
4750 return always_branch;
4751 }
4752 }
4753 unsigned int value = 0;
4754 BoolTest::mask btest = BoolTest::illegal;
4755 switch(kind) {
4756 case RefArray:
4757 case NonRefArray: {
4758 value = Klass::_lh_array_tag_ref_value;
4759 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4760 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4761 break;
4762 }
4763 case TypeArray: {
4764 value = Klass::_lh_array_tag_type_value;
4765 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4766 btest = BoolTest::eq;
4767 break;
4768 }
4769 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4770 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4771 default:
4772 ShouldNotReachHere();
4773 }
4774 // Now test the correct condition.
4775 jint nval = (jint)value;
4776 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4777 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4778 Node* ctrl = generate_fair_guard(bol, region);
4779 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4780 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4781 // Keep track of the fact that 'obj' is an array to prevent
4782 // array specific accesses from floating above the guard.
4783 *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4784 }
4785 return ctrl;
4786 }
4787
4788 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4789 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4790 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4791 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4792 assert(null_free || atomic, "nullable implies atomic");
4793 Node* componentType = argument(0);
4794 Node* length = argument(1);
4795 Node* init_val = null_free ? argument(2) : nullptr;
4796
4797 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4798 if (tp != nullptr) {
4799 ciInstanceKlass* ik = tp->instance_klass();
4800 if (ik == C->env()->Class_klass()) {
4801 ciType* t = tp->java_mirror_type();
4802 if (t != nullptr && t->is_inlinetype()) {
4803
4804 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4805 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4806 assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4807
4808 // TOOD 8350865 ZGC needs card marks on initializing oop stores
4809 if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4810 return false;
4811 }
4812
4813 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4814 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4815 if (null_free) {
4816 if (init_val->is_InlineType()) {
4817 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4818 // Zeroing is enough because the init value is the all-zero value
4819 init_val = nullptr;
4820 } else {
4821 init_val = init_val->as_InlineType()->buffer(this);
4822 }
4823 }
4824 // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4825 }
4826 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4827 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4828 assert(arytype->is_null_free() == null_free, "inconsistency");
4829 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4830 assert(arytype->is_atomic() == atomic, "inconsistency");
4831 set_result(obj);
4832 return true;
4833 }
4834 }
4835 }
4836 }
4837 return false;
4838 }
4839
4840 // public static native boolean ValueClass::isFlatArray(Object array);
4841 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4842 // public static native boolean ValueClass::isAtomicArray(Object array);
4843 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4844 Node* array = argument(0);
4845
4846 Node* bol;
4847 switch(check) {
4848 case IsFlat:
4849 // TODO 8350865 Use the object version here instead of loading the klass
4850 // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4851 bol = flat_array_test(load_object_klass(array));
4852 break;
4853 case IsNullRestricted:
4854 bol = null_free_array_test(array);
4855 break;
4856 case IsAtomic:
4857 // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4858 // Enable TestIntrinsics::test87/88 once this is implemented
4859 // bol = null_free_atomic_array_test
4860 return false;
4861 default:
4862 ShouldNotReachHere();
4863 }
4864
4865 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4866 set_result(res);
4867 return true;
4868 }
4869
4870 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4871 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4872 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4873 RegionNode* region = new RegionNode(2);
4874 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4875
4876 if (type_array_guard) {
4877 generate_typeArray_guard(klass_node, region);
4878 if (region->req() == 3) {
4879 phi->add_req(klass_node);
4880 }
4881 }
4882 Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4883 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4884
4885 // Can be null if not initialized yet, just deopt
4886 Node* null_ctl = top();
4887 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4888
4889 region->init_req(1, control());
4890 phi->init_req(1, refined_klass);
4891
4892 set_control(_gvn.transform(region));
4893 return _gvn.transform(phi);
4894 }
4895
4896 //-----------------------inline_native_newArray--------------------------
4897 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4898 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4899 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4900 Node* mirror;
4901 Node* count_val;
4902 if (uninitialized) {
4903 null_check_receiver();
4904 mirror = argument(1);
4905 count_val = argument(2);
4906 } else {
4907 mirror = argument(0);
4908 count_val = argument(1);
4909 }
4910
4911 mirror = null_check(mirror);
4912 // If mirror or obj is dead, only null-path is taken.
4913 if (stopped()) return true;
4914
4915 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4916 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4917 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4918 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4919 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4920
4921 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4922 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4923 result_reg, _slow_path);
4924 Node* normal_ctl = control();
4925 Node* no_array_ctl = result_reg->in(_slow_path);
4926
4927 // Generate code for the slow case. We make a call to newArray().
4928 set_control(no_array_ctl);
4929 if (!stopped()) {
4930 // Either the input type is void.class, or else the
4931 // array klass has not yet been cached. Either the
4932 // ensuing call will throw an exception, or else it
4933 // will cache the array klass for next time.
4934 PreserveJVMState pjvms(this);
4935 CallJavaNode* slow_call = nullptr;
4936 if (uninitialized) {
4937 // Generate optimized virtual call (holder class 'Unsafe' is final)
4938 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4939 } else {
4940 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4941 }
4942 Node* slow_result = set_results_for_java_call(slow_call);
4943 // this->control() comes from set_results_for_java_call
4944 result_reg->set_req(_slow_path, control());
4945 result_val->set_req(_slow_path, slow_result);
4946 result_io ->set_req(_slow_path, i_o());
4947 result_mem->set_req(_slow_path, reset_memory());
4948 }
4949
4950 set_control(normal_ctl);
4951 if (!stopped()) {
4952 // Normal case: The array type has been cached in the java.lang.Class.
4953 // The following call works fine even if the array type is polymorphic.
4954 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4955
4956 klass_node = load_default_refined_array_klass(klass_node);
4957
4958 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4959 result_reg->init_req(_normal_path, control());
4960 result_val->init_req(_normal_path, obj);
4961 result_io ->init_req(_normal_path, i_o());
4962 result_mem->init_req(_normal_path, reset_memory());
4963
4964 if (uninitialized) {
4965 // Mark the allocation so that zeroing is skipped
4966 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4967 alloc->maybe_set_complete(&_gvn);
4968 }
4969 }
4970
4971 // Return the combined state.
4972 set_i_o( _gvn.transform(result_io) );
4973 set_all_memory( _gvn.transform(result_mem));
4974
4975 C->set_has_split_ifs(true); // Has chance for split-if optimization
4976 set_result(result_reg, result_val);
4977 return true;
4978 }
4979
4980 //----------------------inline_native_getLength--------------------------
4981 // public static native int java.lang.reflect.Array.getLength(Object array);
4982 bool LibraryCallKit::inline_native_getLength() {
4983 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
4984
4985 Node* array = null_check(argument(0));
4986 // If array is dead, only null-path is taken.
4987 if (stopped()) return true;
4988
4989 // Deoptimize if it is a non-array.
4990 Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4991
4992 if (non_array != nullptr) {
4993 PreserveJVMState pjvms(this);
4994 set_control(non_array);
4995 uncommon_trap(Deoptimization::Reason_intrinsic,
4996 Deoptimization::Action_maybe_recompile);
4997 }
4998
4999 // If control is dead, only non-array-path is taken.
5000 if (stopped()) return true;
5001
5002 // The works fine even if the array type is polymorphic.
5003 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5004 Node* result = load_array_length(array);
5005
5006 C->set_has_split_ifs(true); // Has chance for split-if optimization
5007 set_result(result);
5008 return true;
5009 }
5010
5011 //------------------------inline_array_copyOf----------------------------
5012 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
5013 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
5014 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5015 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
5016
5017 // Get the arguments.
5018 Node* original = argument(0);
5019 Node* start = is_copyOfRange? argument(1): intcon(0);
5020 Node* end = is_copyOfRange? argument(2): argument(1);
5021 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5022
5023 Node* newcopy = nullptr;
5024
5025 // Set the original stack and the reexecute bit for the interpreter to reexecute
5026 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5027 { PreserveReexecuteState preexecs(this);
5028 jvms()->set_should_reexecute(true);
5029
5030 array_type_mirror = null_check(array_type_mirror);
5031 original = null_check(original);
5032
5033 // Check if a null path was taken unconditionally.
5034 if (stopped()) return true;
5035
5036 Node* orig_length = load_array_length(original);
5037
5038 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5039 klass_node = null_check(klass_node);
5040
5041 RegionNode* bailout = new RegionNode(1);
5042 record_for_igvn(bailout);
5043
5044 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5045 // Bail out if that is so.
5046 // Inline type array may have object field that would require a
5047 // write barrier. Conservatively, go to slow path.
5048 // TODO 8251971: Optimize for the case when flat src/dst are later found
5049 // to not contain oops (i.e., move this check to the macro expansion phase).
5050 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5051 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5052 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5053 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5054 // Can src array be flat and contain oops?
5055 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5056 // Can dest array be flat and contain oops?
5057 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5058 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5059
5060 klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5061
5062 if (not_objArray != nullptr) {
5063 // Improve the klass node's type from the new optimistic assumption:
5064 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5065 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5066 Node* cast = new CastPPNode(control(), klass_node, akls);
5067 klass_node = _gvn.transform(cast);
5068 }
5069
5070 // Bail out if either start or end is negative.
5071 generate_negative_guard(start, bailout, &start);
5072 generate_negative_guard(end, bailout, &end);
5073
5074 Node* length = end;
5075 if (_gvn.type(start) != TypeInt::ZERO) {
5076 length = _gvn.transform(new SubINode(end, start));
5077 }
5078
5079 // Bail out if length is negative (i.e., if start > end).
5080 // Without this the new_array would throw
5081 // NegativeArraySizeException but IllegalArgumentException is what
5082 // should be thrown
5083 generate_negative_guard(length, bailout, &length);
5084
5085 // Handle inline type arrays
5086 bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5087 if (!stopped()) {
5088 // TODO JDK-8329224
5089 if (!orig_t->is_null_free()) {
5090 // Not statically known to be null free, add a check
5091 generate_fair_guard(null_free_array_test(original), bailout);
5092 }
5093 orig_t = _gvn.type(original)->isa_aryptr();
5094 if (orig_t != nullptr && orig_t->is_flat()) {
5095 // Src is flat, check that dest is flat as well
5096 if (exclude_flat) {
5097 // Dest can't be flat, bail out
5098 bailout->add_req(control());
5099 set_control(top());
5100 } else {
5101 generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
5102 }
5103 // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5104 } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5105 // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5106 ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5107 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5108 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5109 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5110 if (orig_t != nullptr) {
5111 orig_t = orig_t->cast_to_not_flat();
5112 original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5113 }
5114 }
5115 if (!can_validate) {
5116 // No validation. The subtype check emitted at macro expansion time will not go to the slow
5117 // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5118 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5119 generate_fair_guard(flat_array_test(klass_node), bailout);
5120 generate_fair_guard(null_free_array_test(original), bailout);
5121 }
5122 }
5123
5124 // Bail out if start is larger than the original length
5125 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5126 generate_negative_guard(orig_tail, bailout, &orig_tail);
5127
5128 if (bailout->req() > 1) {
5129 PreserveJVMState pjvms(this);
5130 set_control(_gvn.transform(bailout));
5131 uncommon_trap(Deoptimization::Reason_intrinsic,
5132 Deoptimization::Action_maybe_recompile);
5133 }
5134
5135 if (!stopped()) {
5136 // How many elements will we copy from the original?
5137 // The answer is MinI(orig_tail, length).
5138 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5139
5140 // Generate a direct call to the right arraycopy function(s).
5141 // We know the copy is disjoint but we might not know if the
5142 // oop stores need checking.
5143 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5144 // This will fail a store-check if x contains any non-nulls.
5145
5146 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5147 // loads/stores but it is legal only if we're sure the
5148 // Arrays.copyOf would succeed. So we need all input arguments
5149 // to the copyOf to be validated, including that the copy to the
5150 // new array won't trigger an ArrayStoreException. That subtype
5151 // check can be optimized if we know something on the type of
5152 // the input array from type speculation.
5153 if (_gvn.type(klass_node)->singleton()) {
5154 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5155 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5156
5157 int test = C->static_subtype_check(superk, subk);
5158 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5159 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5160 if (t_original->speculative_type() != nullptr) {
5161 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5162 }
5163 }
5164 }
5165
5166 bool validated = false;
5167 // Reason_class_check rather than Reason_intrinsic because we
5168 // want to intrinsify even if this traps.
5169 if (can_validate) {
5170 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5171
5172 if (not_subtype_ctrl != top()) {
5173 PreserveJVMState pjvms(this);
5174 set_control(not_subtype_ctrl);
5175 uncommon_trap(Deoptimization::Reason_class_check,
5176 Deoptimization::Action_make_not_entrant);
5177 assert(stopped(), "Should be stopped");
5178 }
5179 validated = true;
5180 }
5181
5182 if (!stopped()) {
5183 newcopy = new_array(klass_node, length, 0); // no arguments to push
5184
5185 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5186 load_object_klass(original), klass_node);
5187 if (!is_copyOfRange) {
5188 ac->set_copyof(validated);
5189 } else {
5190 ac->set_copyofrange(validated);
5191 }
5192 Node* n = _gvn.transform(ac);
5193 if (n == ac) {
5194 ac->connect_outputs(this);
5195 } else {
5196 assert(validated, "shouldn't transform if all arguments not validated");
5197 set_all_memory(n);
5198 }
5199 }
5200 }
5201 } // original reexecute is set back here
5202
5203 C->set_has_split_ifs(true); // Has chance for split-if optimization
5204 if (!stopped()) {
5205 set_result(newcopy);
5206 }
5207 return true;
5208 }
5209
5210
5211 //----------------------generate_virtual_guard---------------------------
5212 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
5213 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5214 RegionNode* slow_region) {
5215 ciMethod* method = callee();
5216 int vtable_index = method->vtable_index();
5217 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5218 "bad index %d", vtable_index);
5219 // Get the Method* out of the appropriate vtable entry.
5220 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5221 vtable_index*vtableEntry::size_in_bytes() +
5222 in_bytes(vtableEntry::method_offset());
5223 Node* entry_addr = basic_plus_adr(obj_klass, entry_offset);
5224 Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5225
5226 // Compare the target method with the expected method (e.g., Object.hashCode).
5227 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5228
5229 Node* native_call = makecon(native_call_addr);
5230 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
5231 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5232
5233 return generate_slow_guard(test_native, slow_region);
5234 }
5235
5236 //-----------------------generate_method_call----------------------------
5237 // Use generate_method_call to make a slow-call to the real
5238 // method if the fast path fails. An alternative would be to
5239 // use a stub like OptoRuntime::slow_arraycopy_Java.
5240 // This only works for expanding the current library call,
5241 // not another intrinsic. (E.g., don't use this for making an
5242 // arraycopy call inside of the copyOf intrinsic.)
5243 CallJavaNode*
5244 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5245 // When compiling the intrinsic method itself, do not use this technique.
5246 guarantee(callee() != C->method(), "cannot make slow-call to self");
5247
5248 ciMethod* method = callee();
5249 // ensure the JVMS we have will be correct for this call
5250 guarantee(method_id == method->intrinsic_id(), "must match");
5251
5252 const TypeFunc* tf = TypeFunc::make(method);
5253 if (res_not_null) {
5254 assert(tf->return_type() == T_OBJECT, "");
5255 const TypeTuple* range = tf->range_cc();
5256 const Type** fields = TypeTuple::fields(range->cnt());
5257 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5258 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5259 tf = TypeFunc::make(tf->domain_cc(), new_range);
5260 }
5261 CallJavaNode* slow_call;
5262 if (is_static) {
5263 assert(!is_virtual, "");
5264 slow_call = new CallStaticJavaNode(C, tf,
5265 SharedRuntime::get_resolve_static_call_stub(), method);
5266 } else if (is_virtual) {
5267 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5268 int vtable_index = Method::invalid_vtable_index;
5269 if (UseInlineCaches) {
5270 // Suppress the vtable call
5271 } else {
5272 // hashCode and clone are not a miranda methods,
5273 // so the vtable index is fixed.
5274 // No need to use the linkResolver to get it.
5275 vtable_index = method->vtable_index();
5276 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5277 "bad index %d", vtable_index);
5278 }
5279 slow_call = new CallDynamicJavaNode(tf,
5280 SharedRuntime::get_resolve_virtual_call_stub(),
5281 method, vtable_index);
5282 } else { // neither virtual nor static: opt_virtual
5283 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5284 slow_call = new CallStaticJavaNode(C, tf,
5285 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5286 slow_call->set_optimized_virtual(true);
5287 }
5288 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5289 // To be able to issue a direct call (optimized virtual or virtual)
5290 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5291 // about the method being invoked should be attached to the call site to
5292 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5293 slow_call->set_override_symbolic_info(true);
5294 }
5295 set_arguments_for_java_call(slow_call);
5296 set_edges_for_java_call(slow_call);
5297 return slow_call;
5298 }
5299
5300
5301 /**
5302 * Build special case code for calls to hashCode on an object. This call may
5303 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5304 * slightly different code.
5305 */
5306 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5307 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5308 assert(!(is_virtual && is_static), "either virtual, special, or static");
5309
5310 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5311
5312 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5313 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5314 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5315 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5316 Node* obj = argument(0);
5317
5318 // Don't intrinsify hashcode on inline types for now.
5319 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5320 if (gvn().type(obj)->is_inlinetypeptr()) {
5321 return false;
5322 }
5323
5324 if (!is_static) {
5325 // Check for hashing null object
5326 obj = null_check_receiver();
5327 if (stopped()) return true; // unconditionally null
5328 result_reg->init_req(_null_path, top());
5329 result_val->init_req(_null_path, top());
5330 } else {
5331 // Do a null check, and return zero if null.
5332 // System.identityHashCode(null) == 0
5333 Node* null_ctl = top();
5334 obj = null_check_oop(obj, &null_ctl);
5335 result_reg->init_req(_null_path, null_ctl);
5336 result_val->init_req(_null_path, _gvn.intcon(0));
5337 }
5338
5339 // Unconditionally null? Then return right away.
5340 if (stopped()) {
5341 set_control( result_reg->in(_null_path));
5342 if (!stopped())
5343 set_result(result_val->in(_null_path));
5344 return true;
5345 }
5346
5347 // We only go to the fast case code if we pass a number of guards. The
5348 // paths which do not pass are accumulated in the slow_region.
5349 RegionNode* slow_region = new RegionNode(1);
5350 record_for_igvn(slow_region);
5351
5352 // If this is a virtual call, we generate a funny guard. We pull out
5353 // the vtable entry corresponding to hashCode() from the target object.
5354 // If the target method which we are calling happens to be the native
5355 // Object hashCode() method, we pass the guard. We do not need this
5356 // guard for non-virtual calls -- the caller is known to be the native
5357 // Object hashCode().
5358 if (is_virtual) {
5359 // After null check, get the object's klass.
5360 Node* obj_klass = load_object_klass(obj);
5361 generate_virtual_guard(obj_klass, slow_region);
5362 }
5363
5364 // Get the header out of the object, use LoadMarkNode when available
5365 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5366 // The control of the load must be null. Otherwise, the load can move before
5367 // the null check after castPP removal.
5368 Node* no_ctrl = nullptr;
5369 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5370
5371 if (!UseObjectMonitorTable) {
5372 // Test the header to see if it is safe to read w.r.t. locking.
5373 // We cannot use the inline type mask as this may check bits that are overriden
5374 // by an object monitor's pointer when inflating locking.
5375 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5376 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5377 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5378 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5379 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5380
5381 generate_slow_guard(test_monitor, slow_region);
5382 }
5383
5384 // Get the hash value and check to see that it has been properly assigned.
5385 // We depend on hash_mask being at most 32 bits and avoid the use of
5386 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5387 // vm: see markWord.hpp.
5388 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5389 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5390 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5391 // This hack lets the hash bits live anywhere in the mark object now, as long
5392 // as the shift drops the relevant bits into the low 32 bits. Note that
5393 // Java spec says that HashCode is an int so there's no point in capturing
5394 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5395 hshifted_header = ConvX2I(hshifted_header);
5396 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5397
5398 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
5399 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5400 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5401
5402 generate_slow_guard(test_assigned, slow_region);
5403
5404 Node* init_mem = reset_memory();
5405 // fill in the rest of the null path:
5406 result_io ->init_req(_null_path, i_o());
5407 result_mem->init_req(_null_path, init_mem);
5408
5409 result_val->init_req(_fast_path, hash_val);
5410 result_reg->init_req(_fast_path, control());
5411 result_io ->init_req(_fast_path, i_o());
5412 result_mem->init_req(_fast_path, init_mem);
5413
5414 // Generate code for the slow case. We make a call to hashCode().
5415 set_control(_gvn.transform(slow_region));
5416 if (!stopped()) {
5417 // No need for PreserveJVMState, because we're using up the present state.
5418 set_all_memory(init_mem);
5419 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5420 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5421 Node* slow_result = set_results_for_java_call(slow_call);
5422 // this->control() comes from set_results_for_java_call
5423 result_reg->init_req(_slow_path, control());
5424 result_val->init_req(_slow_path, slow_result);
5425 result_io ->set_req(_slow_path, i_o());
5426 result_mem ->set_req(_slow_path, reset_memory());
5427 }
5428
5429 // Return the combined state.
5430 set_i_o( _gvn.transform(result_io) );
5431 set_all_memory( _gvn.transform(result_mem));
5432
5433 set_result(result_reg, result_val);
5434 return true;
5435 }
5436
5437 //---------------------------inline_native_getClass----------------------------
5438 // public final native Class<?> java.lang.Object.getClass();
5439 //
5440 // Build special case code for calls to getClass on an object.
5441 bool LibraryCallKit::inline_native_getClass() {
5442 Node* obj = argument(0);
5443 if (obj->is_InlineType()) {
5444 const Type* t = _gvn.type(obj);
5445 if (t->maybe_null()) {
5446 null_check(obj);
5447 }
5448 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5449 return true;
5450 }
5451 obj = null_check_receiver();
5452 if (stopped()) return true;
5453 set_result(load_mirror_from_klass(load_object_klass(obj)));
5454 return true;
5455 }
5456
5457 //-----------------inline_native_Reflection_getCallerClass---------------------
5458 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5459 //
5460 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5461 //
5462 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5463 // in that it must skip particular security frames and checks for
5464 // caller sensitive methods.
5465 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5466 #ifndef PRODUCT
5467 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5468 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5469 }
5470 #endif
5471
5472 if (!jvms()->has_method()) {
5473 #ifndef PRODUCT
5474 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5475 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
5476 }
5477 #endif
5478 return false;
5479 }
5480
5481 // Walk back up the JVM state to find the caller at the required
5482 // depth.
5483 JVMState* caller_jvms = jvms();
5484
5485 // Cf. JVM_GetCallerClass
5486 // NOTE: Start the loop at depth 1 because the current JVM state does
5487 // not include the Reflection.getCallerClass() frame.
5488 for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5489 ciMethod* m = caller_jvms->method();
5490 switch (n) {
5491 case 0:
5492 fatal("current JVM state does not include the Reflection.getCallerClass frame");
5493 break;
5494 case 1:
5495 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5496 if (!m->caller_sensitive()) {
5497 #ifndef PRODUCT
5498 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5499 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
5500 }
5501 #endif
5502 return false; // bail-out; let JVM_GetCallerClass do the work
5503 }
5504 break;
5505 default:
5506 if (!m->is_ignored_by_security_stack_walk()) {
5507 // We have reached the desired frame; return the holder class.
5508 // Acquire method holder as java.lang.Class and push as constant.
5509 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5510 ciInstance* caller_mirror = caller_klass->java_mirror();
5511 set_result(makecon(TypeInstPtr::make(caller_mirror)));
5512
5513 #ifndef PRODUCT
5514 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5515 tty->print_cr(" Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
5516 tty->print_cr(" JVM state at this point:");
5517 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5518 ciMethod* m = jvms()->of_depth(i)->method();
5519 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5520 }
5521 }
5522 #endif
5523 return true;
5524 }
5525 break;
5526 }
5527 }
5528
5529 #ifndef PRODUCT
5530 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5531 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5532 tty->print_cr(" JVM state at this point:");
5533 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5534 ciMethod* m = jvms()->of_depth(i)->method();
5535 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5536 }
5537 }
5538 #endif
5539
5540 return false; // bail-out; let JVM_GetCallerClass do the work
5541 }
5542
5543 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5544 Node* arg = argument(0);
5545 Node* result = nullptr;
5546
5547 switch (id) {
5548 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
5549 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
5550 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
5551 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
5552 case vmIntrinsics::_floatToFloat16: result = new ConvF2HFNode(arg); break;
5553 case vmIntrinsics::_float16ToFloat: result = new ConvHF2FNode(arg); break;
5554
5555 case vmIntrinsics::_doubleToLongBits: {
5556 // two paths (plus control) merge in a wood
5557 RegionNode *r = new RegionNode(3);
5558 Node *phi = new PhiNode(r, TypeLong::LONG);
5559
5560 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5561 // Build the boolean node
5562 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5563
5564 // Branch either way.
5565 // NaN case is less traveled, which makes all the difference.
5566 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5567 Node *opt_isnan = _gvn.transform(ifisnan);
5568 assert( opt_isnan->is_If(), "Expect an IfNode");
5569 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5570 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5571
5572 set_control(iftrue);
5573
5574 static const jlong nan_bits = CONST64(0x7ff8000000000000);
5575 Node *slow_result = longcon(nan_bits); // return NaN
5576 phi->init_req(1, _gvn.transform( slow_result ));
5577 r->init_req(1, iftrue);
5578
5579 // Else fall through
5580 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5581 set_control(iffalse);
5582
5583 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5584 r->init_req(2, iffalse);
5585
5586 // Post merge
5587 set_control(_gvn.transform(r));
5588 record_for_igvn(r);
5589
5590 C->set_has_split_ifs(true); // Has chance for split-if optimization
5591 result = phi;
5592 assert(result->bottom_type()->isa_long(), "must be");
5593 break;
5594 }
5595
5596 case vmIntrinsics::_floatToIntBits: {
5597 // two paths (plus control) merge in a wood
5598 RegionNode *r = new RegionNode(3);
5599 Node *phi = new PhiNode(r, TypeInt::INT);
5600
5601 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5602 // Build the boolean node
5603 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5604
5605 // Branch either way.
5606 // NaN case is less traveled, which makes all the difference.
5607 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5608 Node *opt_isnan = _gvn.transform(ifisnan);
5609 assert( opt_isnan->is_If(), "Expect an IfNode");
5610 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5611 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5612
5613 set_control(iftrue);
5614
5615 static const jint nan_bits = 0x7fc00000;
5616 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5617 phi->init_req(1, _gvn.transform( slow_result ));
5618 r->init_req(1, iftrue);
5619
5620 // Else fall through
5621 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5622 set_control(iffalse);
5623
5624 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5625 r->init_req(2, iffalse);
5626
5627 // Post merge
5628 set_control(_gvn.transform(r));
5629 record_for_igvn(r);
5630
5631 C->set_has_split_ifs(true); // Has chance for split-if optimization
5632 result = phi;
5633 assert(result->bottom_type()->isa_int(), "must be");
5634 break;
5635 }
5636
5637 default:
5638 fatal_unexpected_iid(id);
5639 break;
5640 }
5641 set_result(_gvn.transform(result));
5642 return true;
5643 }
5644
5645 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5646 Node* arg = argument(0);
5647 Node* result = nullptr;
5648
5649 switch (id) {
5650 case vmIntrinsics::_floatIsInfinite:
5651 result = new IsInfiniteFNode(arg);
5652 break;
5653 case vmIntrinsics::_floatIsFinite:
5654 result = new IsFiniteFNode(arg);
5655 break;
5656 case vmIntrinsics::_doubleIsInfinite:
5657 result = new IsInfiniteDNode(arg);
5658 break;
5659 case vmIntrinsics::_doubleIsFinite:
5660 result = new IsFiniteDNode(arg);
5661 break;
5662 default:
5663 fatal_unexpected_iid(id);
5664 break;
5665 }
5666 set_result(_gvn.transform(result));
5667 return true;
5668 }
5669
5670 //----------------------inline_unsafe_copyMemory-------------------------
5671 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5672
5673 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5674 const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5675 const Type* base_t = gvn.type(base);
5676
5677 bool in_native = (base_t == TypePtr::NULL_PTR);
5678 bool in_heap = !TypePtr::NULL_PTR->higher_equal(base_t);
5679 bool is_mixed = !in_heap && !in_native;
5680
5681 if (is_mixed) {
5682 return true; // mixed accesses can touch both on-heap and off-heap memory
5683 }
5684 if (in_heap) {
5685 bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5686 if (!is_prim_array) {
5687 // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5688 // there's not enough type information available to determine proper memory slice for it.
5689 return true;
5690 }
5691 }
5692 return false;
5693 }
5694
5695 bool LibraryCallKit::inline_unsafe_copyMemory() {
5696 if (callee()->is_static()) return false; // caller must have the capability!
5697 null_check_receiver(); // null-check receiver
5698 if (stopped()) return true;
5699
5700 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5701
5702 Node* src_base = argument(1); // type: oop
5703 Node* src_off = ConvL2X(argument(2)); // type: long
5704 Node* dst_base = argument(4); // type: oop
5705 Node* dst_off = ConvL2X(argument(5)); // type: long
5706 Node* size = ConvL2X(argument(7)); // type: long
5707
5708 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5709 "fieldOffset must be byte-scaled");
5710
5711 Node* src_addr = make_unsafe_address(src_base, src_off);
5712 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5713
5714 Node* thread = _gvn.transform(new ThreadLocalNode());
5715 Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5716 BasicType doing_unsafe_access_bt = T_BYTE;
5717 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5718
5719 // update volatile field
5720 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5721
5722 int flags = RC_LEAF | RC_NO_FP;
5723
5724 const TypePtr* dst_type = TypePtr::BOTTOM;
5725
5726 // Adjust memory effects of the runtime call based on input values.
5727 if (!has_wide_mem(_gvn, src_addr, src_base) &&
5728 !has_wide_mem(_gvn, dst_addr, dst_base)) {
5729 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5730
5731 const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5732 if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5733 flags |= RC_NARROW_MEM; // narrow in memory
5734 }
5735 }
5736
5737 // Call it. Note that the length argument is not scaled.
5738 make_runtime_call(flags,
5739 OptoRuntime::fast_arraycopy_Type(),
5740 StubRoutines::unsafe_arraycopy(),
5741 "unsafe_arraycopy",
5742 dst_type,
5743 src_addr, dst_addr, size XTOP);
5744
5745 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5746
5747 return true;
5748 }
5749
5750 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5751 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5752 bool LibraryCallKit::inline_unsafe_setMemory() {
5753 if (callee()->is_static()) return false; // caller must have the capability!
5754 null_check_receiver(); // null-check receiver
5755 if (stopped()) return true;
5756
5757 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5758
5759 Node* dst_base = argument(1); // type: oop
5760 Node* dst_off = ConvL2X(argument(2)); // type: long
5761 Node* size = ConvL2X(argument(4)); // type: long
5762 Node* byte = argument(6); // type: byte
5763
5764 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5765 "fieldOffset must be byte-scaled");
5766
5767 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5768
5769 Node* thread = _gvn.transform(new ThreadLocalNode());
5770 Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5771 BasicType doing_unsafe_access_bt = T_BYTE;
5772 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5773
5774 // update volatile field
5775 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5776
5777 int flags = RC_LEAF | RC_NO_FP;
5778
5779 const TypePtr* dst_type = TypePtr::BOTTOM;
5780
5781 // Adjust memory effects of the runtime call based on input values.
5782 if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5783 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5784
5785 flags |= RC_NARROW_MEM; // narrow in memory
5786 }
5787
5788 // Call it. Note that the length argument is not scaled.
5789 make_runtime_call(flags,
5790 OptoRuntime::unsafe_setmemory_Type(),
5791 StubRoutines::unsafe_setmemory(),
5792 "unsafe_setmemory",
5793 dst_type,
5794 dst_addr, size XTOP, byte);
5795
5796 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5797
5798 return true;
5799 }
5800
5801 #undef XTOP
5802
5803 //------------------------clone_coping-----------------------------------
5804 // Helper function for inline_native_clone.
5805 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5806 assert(obj_size != nullptr, "");
5807 Node* raw_obj = alloc_obj->in(1);
5808 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5809
5810 AllocateNode* alloc = nullptr;
5811 if (ReduceBulkZeroing &&
5812 // If we are implementing an array clone without knowing its source type
5813 // (can happen when compiling the array-guarded branch of a reflective
5814 // Object.clone() invocation), initialize the array within the allocation.
5815 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5816 // to a runtime clone call that assumes fully initialized source arrays.
5817 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5818 // We will be completely responsible for initializing this object -
5819 // mark Initialize node as complete.
5820 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5821 // The object was just allocated - there should be no any stores!
5822 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5823 // Mark as complete_with_arraycopy so that on AllocateNode
5824 // expansion, we know this AllocateNode is initialized by an array
5825 // copy and a StoreStore barrier exists after the array copy.
5826 alloc->initialization()->set_complete_with_arraycopy();
5827 }
5828
5829 Node* size = _gvn.transform(obj_size);
5830 access_clone(obj, alloc_obj, size, is_array);
5831
5832 // Do not let reads from the cloned object float above the arraycopy.
5833 if (alloc != nullptr) {
5834 // Do not let stores that initialize this object be reordered with
5835 // a subsequent store that would make this object accessible by
5836 // other threads.
5837 // Record what AllocateNode this StoreStore protects so that
5838 // escape analysis can go from the MemBarStoreStoreNode to the
5839 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5840 // based on the escape status of the AllocateNode.
5841 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5842 } else {
5843 insert_mem_bar(Op_MemBarCPUOrder);
5844 }
5845 }
5846
5847 //------------------------inline_native_clone----------------------------
5848 // protected native Object java.lang.Object.clone();
5849 //
5850 // Here are the simple edge cases:
5851 // null receiver => normal trap
5852 // virtual and clone was overridden => slow path to out-of-line clone
5853 // not cloneable or finalizer => slow path to out-of-line Object.clone
5854 //
5855 // The general case has two steps, allocation and copying.
5856 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5857 //
5858 // Copying also has two cases, oop arrays and everything else.
5859 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5860 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5861 //
5862 // These steps fold up nicely if and when the cloned object's klass
5863 // can be sharply typed as an object array, a type array, or an instance.
5864 //
5865 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5866 PhiNode* result_val;
5867
5868 // Set the reexecute bit for the interpreter to reexecute
5869 // the bytecode that invokes Object.clone if deoptimization happens.
5870 { PreserveReexecuteState preexecs(this);
5871 jvms()->set_should_reexecute(true);
5872
5873 Node* obj = argument(0);
5874 obj = null_check_receiver();
5875 if (stopped()) return true;
5876
5877 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5878 if (obj_type->is_inlinetypeptr()) {
5879 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5880 // no identity.
5881 set_result(obj);
5882 return true;
5883 }
5884
5885 // If we are going to clone an instance, we need its exact type to
5886 // know the number and types of fields to convert the clone to
5887 // loads/stores. Maybe a speculative type can help us.
5888 if (!obj_type->klass_is_exact() &&
5889 obj_type->speculative_type() != nullptr &&
5890 obj_type->speculative_type()->is_instance_klass() &&
5891 !obj_type->speculative_type()->is_inlinetype()) {
5892 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5893 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5894 !spec_ik->has_injected_fields()) {
5895 if (!obj_type->isa_instptr() ||
5896 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5897 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5898 }
5899 }
5900 }
5901
5902 // Conservatively insert a memory barrier on all memory slices.
5903 // Do not let writes into the original float below the clone.
5904 insert_mem_bar(Op_MemBarCPUOrder);
5905
5906 // paths into result_reg:
5907 enum {
5908 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5909 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5910 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5911 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5912 PATH_LIMIT
5913 };
5914 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5915 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5916 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5917 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5918 record_for_igvn(result_reg);
5919
5920 Node* obj_klass = load_object_klass(obj);
5921 // We only go to the fast case code if we pass a number of guards.
5922 // The paths which do not pass are accumulated in the slow_region.
5923 RegionNode* slow_region = new RegionNode(1);
5924 record_for_igvn(slow_region);
5925
5926 Node* array_obj = obj;
5927 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5928 if (array_ctl != nullptr) {
5929 // It's an array.
5930 PreserveJVMState pjvms(this);
5931 set_control(array_ctl);
5932
5933 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5934 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5935 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5936 obj_type->can_be_inline_array() &&
5937 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5938 // Flat inline type array may have object field that would require a
5939 // write barrier. Conservatively, go to slow path.
5940 generate_fair_guard(flat_array_test(obj_klass), slow_region);
5941 }
5942
5943 if (!stopped()) {
5944 Node* obj_length = load_array_length(array_obj);
5945 Node* array_size = nullptr; // Size of the array without object alignment padding.
5946 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5947
5948 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5949 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5950 // If it is an oop array, it requires very special treatment,
5951 // because gc barriers are required when accessing the array.
5952 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5953 if (is_obja != nullptr) {
5954 PreserveJVMState pjvms2(this);
5955 set_control(is_obja);
5956 // Generate a direct call to the right arraycopy function(s).
5957 // Clones are always tightly coupled.
5958 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5959 ac->set_clone_oop_array();
5960 Node* n = _gvn.transform(ac);
5961 assert(n == ac, "cannot disappear");
5962 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5963
5964 result_reg->init_req(_objArray_path, control());
5965 result_val->init_req(_objArray_path, alloc_obj);
5966 result_i_o ->set_req(_objArray_path, i_o());
5967 result_mem ->set_req(_objArray_path, reset_memory());
5968 }
5969 }
5970 // Otherwise, there are no barriers to worry about.
5971 // (We can dispense with card marks if we know the allocation
5972 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5973 // causes the non-eden paths to take compensating steps to
5974 // simulate a fresh allocation, so that no further
5975 // card marks are required in compiled code to initialize
5976 // the object.)
5977
5978 if (!stopped()) {
5979 copy_to_clone(obj, alloc_obj, array_size, true);
5980
5981 // Present the results of the copy.
5982 result_reg->init_req(_array_path, control());
5983 result_val->init_req(_array_path, alloc_obj);
5984 result_i_o ->set_req(_array_path, i_o());
5985 result_mem ->set_req(_array_path, reset_memory());
5986 }
5987 }
5988 }
5989
5990 if (!stopped()) {
5991 // It's an instance (we did array above). Make the slow-path tests.
5992 // If this is a virtual call, we generate a funny guard. We grab
5993 // the vtable entry corresponding to clone() from the target object.
5994 // If the target method which we are calling happens to be the
5995 // Object clone() method, we pass the guard. We do not need this
5996 // guard for non-virtual calls; the caller is known to be the native
5997 // Object clone().
5998 if (is_virtual) {
5999 generate_virtual_guard(obj_klass, slow_region);
6000 }
6001
6002 // The object must be easily cloneable and must not have a finalizer.
6003 // Both of these conditions may be checked in a single test.
6004 // We could optimize the test further, but we don't care.
6005 generate_misc_flags_guard(obj_klass,
6006 // Test both conditions:
6007 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6008 // Must be cloneable but not finalizer:
6009 KlassFlags::_misc_is_cloneable_fast,
6010 slow_region);
6011 }
6012
6013 if (!stopped()) {
6014 // It's an instance, and it passed the slow-path tests.
6015 PreserveJVMState pjvms(this);
6016 Node* obj_size = nullptr; // Total object size, including object alignment padding.
6017 // Need to deoptimize on exception from allocation since Object.clone intrinsic
6018 // is reexecuted if deoptimization occurs and there could be problems when merging
6019 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6020 Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6021
6022 copy_to_clone(obj, alloc_obj, obj_size, false);
6023
6024 // Present the results of the slow call.
6025 result_reg->init_req(_instance_path, control());
6026 result_val->init_req(_instance_path, alloc_obj);
6027 result_i_o ->set_req(_instance_path, i_o());
6028 result_mem ->set_req(_instance_path, reset_memory());
6029 }
6030
6031 // Generate code for the slow case. We make a call to clone().
6032 set_control(_gvn.transform(slow_region));
6033 if (!stopped()) {
6034 PreserveJVMState pjvms(this);
6035 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6036 // We need to deoptimize on exception (see comment above)
6037 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6038 // this->control() comes from set_results_for_java_call
6039 result_reg->init_req(_slow_path, control());
6040 result_val->init_req(_slow_path, slow_result);
6041 result_i_o ->set_req(_slow_path, i_o());
6042 result_mem ->set_req(_slow_path, reset_memory());
6043 }
6044
6045 // Return the combined state.
6046 set_control( _gvn.transform(result_reg));
6047 set_i_o( _gvn.transform(result_i_o));
6048 set_all_memory( _gvn.transform(result_mem));
6049 } // original reexecute is set back here
6050
6051 set_result(_gvn.transform(result_val));
6052 return true;
6053 }
6054
6055 // If we have a tightly coupled allocation, the arraycopy may take care
6056 // of the array initialization. If one of the guards we insert between
6057 // the allocation and the arraycopy causes a deoptimization, an
6058 // uninitialized array will escape the compiled method. To prevent that
6059 // we set the JVM state for uncommon traps between the allocation and
6060 // the arraycopy to the state before the allocation so, in case of
6061 // deoptimization, we'll reexecute the allocation and the
6062 // initialization.
6063 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6064 if (alloc != nullptr) {
6065 ciMethod* trap_method = alloc->jvms()->method();
6066 int trap_bci = alloc->jvms()->bci();
6067
6068 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6069 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6070 // Make sure there's no store between the allocation and the
6071 // arraycopy otherwise visible side effects could be rexecuted
6072 // in case of deoptimization and cause incorrect execution.
6073 bool no_interfering_store = true;
6074 Node* mem = alloc->in(TypeFunc::Memory);
6075 if (mem->is_MergeMem()) {
6076 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6077 Node* n = mms.memory();
6078 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6079 assert(n->is_Store(), "what else?");
6080 no_interfering_store = false;
6081 break;
6082 }
6083 }
6084 } else {
6085 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6086 Node* n = mms.memory();
6087 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6088 assert(n->is_Store(), "what else?");
6089 no_interfering_store = false;
6090 break;
6091 }
6092 }
6093 }
6094
6095 if (no_interfering_store) {
6096 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6097
6098 JVMState* saved_jvms = jvms();
6099 saved_reexecute_sp = _reexecute_sp;
6100
6101 set_jvms(sfpt->jvms());
6102 _reexecute_sp = jvms()->sp();
6103
6104 return saved_jvms;
6105 }
6106 }
6107 }
6108 return nullptr;
6109 }
6110
6111 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6112 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6113 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6114 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6115 uint size = alloc->req();
6116 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6117 old_jvms->set_map(sfpt);
6118 for (uint i = 0; i < size; i++) {
6119 sfpt->init_req(i, alloc->in(i));
6120 }
6121 int adjustment = 1;
6122 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6123 if (ary_klass_ptr->is_null_free()) {
6124 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6125 // also requires the componentType and initVal on stack for re-execution.
6126 // Re-create and push the componentType.
6127 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6128 ciInstance* instance = klass->component_mirror_instance();
6129 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6130 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6131 adjustment++;
6132 }
6133 // re-push array length for deoptimization
6134 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6135 if (ary_klass_ptr->is_null_free()) {
6136 // Re-create and push the initVal.
6137 Node* init_val = alloc->in(AllocateNode::InitValue);
6138 if (init_val == nullptr) {
6139 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6140 } else if (UseCompressedOops) {
6141 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6142 }
6143 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6144 adjustment++;
6145 }
6146 old_jvms->set_sp(old_jvms->sp() + adjustment);
6147 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6148 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6149 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6150 old_jvms->set_should_reexecute(true);
6151
6152 sfpt->set_i_o(map()->i_o());
6153 sfpt->set_memory(map()->memory());
6154 sfpt->set_control(map()->control());
6155 return sfpt;
6156 }
6157
6158 // In case of a deoptimization, we restart execution at the
6159 // allocation, allocating a new array. We would leave an uninitialized
6160 // array in the heap that GCs wouldn't expect. Move the allocation
6161 // after the traps so we don't allocate the array if we
6162 // deoptimize. This is possible because tightly_coupled_allocation()
6163 // guarantees there's no observer of the allocated array at this point
6164 // and the control flow is simple enough.
6165 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6166 int saved_reexecute_sp, uint new_idx) {
6167 if (saved_jvms_before_guards != nullptr && !stopped()) {
6168 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6169
6170 assert(alloc != nullptr, "only with a tightly coupled allocation");
6171 // restore JVM state to the state at the arraycopy
6172 saved_jvms_before_guards->map()->set_control(map()->control());
6173 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6174 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6175 // If we've improved the types of some nodes (null check) while
6176 // emitting the guards, propagate them to the current state
6177 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6178 set_jvms(saved_jvms_before_guards);
6179 _reexecute_sp = saved_reexecute_sp;
6180
6181 // Remove the allocation from above the guards
6182 CallProjections* callprojs = alloc->extract_projections(true);
6183 InitializeNode* init = alloc->initialization();
6184 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6185 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6186 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6187
6188 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6189 // the allocation (i.e. is only valid if the allocation succeeds):
6190 // 1) replace CastIINode with AllocateArrayNode's length here
6191 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6192 //
6193 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6194 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6195 Node* init_control = init->proj_out(TypeFunc::Control);
6196 Node* alloc_length = alloc->Ideal_length();
6197 #ifdef ASSERT
6198 Node* prev_cast = nullptr;
6199 #endif
6200 for (uint i = 0; i < init_control->outcnt(); i++) {
6201 Node* init_out = init_control->raw_out(i);
6202 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6203 #ifdef ASSERT
6204 if (prev_cast == nullptr) {
6205 prev_cast = init_out;
6206 } else {
6207 if (prev_cast->cmp(*init_out) == false) {
6208 prev_cast->dump();
6209 init_out->dump();
6210 assert(false, "not equal CastIINode");
6211 }
6212 }
6213 #endif
6214 C->gvn_replace_by(init_out, alloc_length);
6215 }
6216 }
6217 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6218
6219 // move the allocation here (after the guards)
6220 _gvn.hash_delete(alloc);
6221 alloc->set_req(TypeFunc::Control, control());
6222 alloc->set_req(TypeFunc::I_O, i_o());
6223 Node *mem = reset_memory();
6224 set_all_memory(mem);
6225 alloc->set_req(TypeFunc::Memory, mem);
6226 set_control(init->proj_out_or_null(TypeFunc::Control));
6227 set_i_o(callprojs->fallthrough_ioproj);
6228
6229 // Update memory as done in GraphKit::set_output_for_allocation()
6230 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6231 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6232 if (ary_type->isa_aryptr() && length_type != nullptr) {
6233 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6234 }
6235 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6236 int elemidx = C->get_alias_index(telemref);
6237 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6238 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6239
6240 Node* allocx = _gvn.transform(alloc);
6241 assert(allocx == alloc, "where has the allocation gone?");
6242 assert(dest->is_CheckCastPP(), "not an allocation result?");
6243
6244 _gvn.hash_delete(dest);
6245 dest->set_req(0, control());
6246 Node* destx = _gvn.transform(dest);
6247 assert(destx == dest, "where has the allocation result gone?");
6248
6249 array_ideal_length(alloc, ary_type, true);
6250 }
6251 }
6252
6253 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6254 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6255 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6256 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6257 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6258 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6259 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6260 JVMState* saved_jvms_before_guards) {
6261 if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6262 // There is at least one unrelated uncommon trap which needs to be replaced.
6263 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6264
6265 JVMState* saved_jvms = jvms();
6266 const int saved_reexecute_sp = _reexecute_sp;
6267 set_jvms(sfpt->jvms());
6268 _reexecute_sp = jvms()->sp();
6269
6270 replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6271
6272 // Restore state
6273 set_jvms(saved_jvms);
6274 _reexecute_sp = saved_reexecute_sp;
6275 }
6276 }
6277
6278 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6279 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6280 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6281 Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6282 while (if_proj->is_IfProj()) {
6283 CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6284 if (uncommon_trap != nullptr) {
6285 create_new_uncommon_trap(uncommon_trap);
6286 }
6287 assert(if_proj->in(0)->is_If(), "must be If");
6288 if_proj = if_proj->in(0)->in(0);
6289 }
6290 assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6291 "must have reached control projection of init node");
6292 }
6293
6294 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6295 const int trap_request = uncommon_trap_call->uncommon_trap_request();
6296 assert(trap_request != 0, "no valid UCT trap request");
6297 PreserveJVMState pjvms(this);
6298 set_control(uncommon_trap_call->in(0));
6299 uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6300 Deoptimization::trap_request_action(trap_request));
6301 assert(stopped(), "Should be stopped");
6302 _gvn.hash_delete(uncommon_trap_call);
6303 uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6304 }
6305
6306 // Common checks for array sorting intrinsics arguments.
6307 // Returns `true` if checks passed.
6308 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6309 // check address of the class
6310 if (elementType == nullptr || elementType->is_top()) {
6311 return false; // dead path
6312 }
6313 const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6314 if (elem_klass == nullptr) {
6315 return false; // dead path
6316 }
6317 // java_mirror_type() returns non-null for compile-time Class constants only
6318 ciType* elem_type = elem_klass->java_mirror_type();
6319 if (elem_type == nullptr) {
6320 return false;
6321 }
6322 bt = elem_type->basic_type();
6323 // Disable the intrinsic if the CPU does not support SIMD sort
6324 if (!Matcher::supports_simd_sort(bt)) {
6325 return false;
6326 }
6327 // check address of the array
6328 if (obj == nullptr || obj->is_top()) {
6329 return false; // dead path
6330 }
6331 const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6332 if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6333 return false; // failed input validation
6334 }
6335 return true;
6336 }
6337
6338 //------------------------------inline_array_partition-----------------------
6339 bool LibraryCallKit::inline_array_partition() {
6340 address stubAddr = StubRoutines::select_array_partition_function();
6341 if (stubAddr == nullptr) {
6342 return false; // Intrinsic's stub is not implemented on this platform
6343 }
6344 assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6345
6346 // no receiver because it is a static method
6347 Node* elementType = argument(0);
6348 Node* obj = argument(1);
6349 Node* offset = argument(2); // long
6350 Node* fromIndex = argument(4);
6351 Node* toIndex = argument(5);
6352 Node* indexPivot1 = argument(6);
6353 Node* indexPivot2 = argument(7);
6354 // PartitionOperation: argument(8) is ignored
6355
6356 Node* pivotIndices = nullptr;
6357 BasicType bt = T_ILLEGAL;
6358
6359 if (!check_array_sort_arguments(elementType, obj, bt)) {
6360 return false;
6361 }
6362 null_check(obj);
6363 // If obj is dead, only null-path is taken.
6364 if (stopped()) {
6365 return true;
6366 }
6367 // Set the original stack and the reexecute bit for the interpreter to reexecute
6368 // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6369 { PreserveReexecuteState preexecs(this);
6370 jvms()->set_should_reexecute(true);
6371
6372 Node* obj_adr = make_unsafe_address(obj, offset);
6373
6374 // create the pivotIndices array of type int and size = 2
6375 Node* size = intcon(2);
6376 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6377 pivotIndices = new_array(klass_node, size, 0); // no arguments to push
6378 AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6379 guarantee(alloc != nullptr, "created above");
6380 Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6381
6382 // pass the basic type enum to the stub
6383 Node* elemType = intcon(bt);
6384
6385 // Call the stub
6386 const char *stubName = "array_partition_stub";
6387 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6388 stubAddr, stubName, TypePtr::BOTTOM,
6389 obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6390 indexPivot1, indexPivot2);
6391
6392 } // original reexecute is set back here
6393
6394 if (!stopped()) {
6395 set_result(pivotIndices);
6396 }
6397
6398 return true;
6399 }
6400
6401
6402 //------------------------------inline_array_sort-----------------------
6403 bool LibraryCallKit::inline_array_sort() {
6404 address stubAddr = StubRoutines::select_arraysort_function();
6405 if (stubAddr == nullptr) {
6406 return false; // Intrinsic's stub is not implemented on this platform
6407 }
6408 assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6409
6410 // no receiver because it is a static method
6411 Node* elementType = argument(0);
6412 Node* obj = argument(1);
6413 Node* offset = argument(2); // long
6414 Node* fromIndex = argument(4);
6415 Node* toIndex = argument(5);
6416 // SortOperation: argument(6) is ignored
6417
6418 BasicType bt = T_ILLEGAL;
6419
6420 if (!check_array_sort_arguments(elementType, obj, bt)) {
6421 return false;
6422 }
6423 null_check(obj);
6424 // If obj is dead, only null-path is taken.
6425 if (stopped()) {
6426 return true;
6427 }
6428 Node* obj_adr = make_unsafe_address(obj, offset);
6429
6430 // pass the basic type enum to the stub
6431 Node* elemType = intcon(bt);
6432
6433 // Call the stub.
6434 const char *stubName = "arraysort_stub";
6435 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6436 stubAddr, stubName, TypePtr::BOTTOM,
6437 obj_adr, elemType, fromIndex, toIndex);
6438
6439 return true;
6440 }
6441
6442
6443 //------------------------------inline_arraycopy-----------------------
6444 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
6445 // Object dest, int destPos,
6446 // int length);
6447 bool LibraryCallKit::inline_arraycopy() {
6448 // Get the arguments.
6449 Node* src = argument(0); // type: oop
6450 Node* src_offset = argument(1); // type: int
6451 Node* dest = argument(2); // type: oop
6452 Node* dest_offset = argument(3); // type: int
6453 Node* length = argument(4); // type: int
6454
6455 uint new_idx = C->unique();
6456
6457 // Check for allocation before we add nodes that would confuse
6458 // tightly_coupled_allocation()
6459 AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6460
6461 int saved_reexecute_sp = -1;
6462 JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6463 // See arraycopy_restore_alloc_state() comment
6464 // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6465 // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6466 // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6467 bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6468
6469 // The following tests must be performed
6470 // (1) src and dest are arrays.
6471 // (2) src and dest arrays must have elements of the same BasicType
6472 // (3) src and dest must not be null.
6473 // (4) src_offset must not be negative.
6474 // (5) dest_offset must not be negative.
6475 // (6) length must not be negative.
6476 // (7) src_offset + length must not exceed length of src.
6477 // (8) dest_offset + length must not exceed length of dest.
6478 // (9) each element of an oop array must be assignable
6479
6480 // (3) src and dest must not be null.
6481 // always do this here because we need the JVM state for uncommon traps
6482 Node* null_ctl = top();
6483 src = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6484 assert(null_ctl->is_top(), "no null control here");
6485 dest = null_check(dest, T_ARRAY);
6486
6487 if (!can_emit_guards) {
6488 // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6489 // guards but the arraycopy node could still take advantage of a
6490 // tightly allocated allocation. tightly_coupled_allocation() is
6491 // called again to make sure it takes the null check above into
6492 // account: the null check is mandatory and if it caused an
6493 // uncommon trap to be emitted then the allocation can't be
6494 // considered tightly coupled in this context.
6495 alloc = tightly_coupled_allocation(dest);
6496 }
6497
6498 bool validated = false;
6499
6500 const Type* src_type = _gvn.type(src);
6501 const Type* dest_type = _gvn.type(dest);
6502 const TypeAryPtr* top_src = src_type->isa_aryptr();
6503 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6504
6505 // Do we have the type of src?
6506 bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6507 // Do we have the type of dest?
6508 bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6509 // Is the type for src from speculation?
6510 bool src_spec = false;
6511 // Is the type for dest from speculation?
6512 bool dest_spec = false;
6513
6514 if ((!has_src || !has_dest) && can_emit_guards) {
6515 // We don't have sufficient type information, let's see if
6516 // speculative types can help. We need to have types for both src
6517 // and dest so that it pays off.
6518
6519 // Do we already have or could we have type information for src
6520 bool could_have_src = has_src;
6521 // Do we already have or could we have type information for dest
6522 bool could_have_dest = has_dest;
6523
6524 ciKlass* src_k = nullptr;
6525 if (!has_src) {
6526 src_k = src_type->speculative_type_not_null();
6527 if (src_k != nullptr && src_k->is_array_klass()) {
6528 could_have_src = true;
6529 }
6530 }
6531
6532 ciKlass* dest_k = nullptr;
6533 if (!has_dest) {
6534 dest_k = dest_type->speculative_type_not_null();
6535 if (dest_k != nullptr && dest_k->is_array_klass()) {
6536 could_have_dest = true;
6537 }
6538 }
6539
6540 if (could_have_src && could_have_dest) {
6541 // This is going to pay off so emit the required guards
6542 if (!has_src) {
6543 src = maybe_cast_profiled_obj(src, src_k, true);
6544 src_type = _gvn.type(src);
6545 top_src = src_type->isa_aryptr();
6546 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6547 src_spec = true;
6548 }
6549 if (!has_dest) {
6550 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6551 dest_type = _gvn.type(dest);
6552 top_dest = dest_type->isa_aryptr();
6553 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6554 dest_spec = true;
6555 }
6556 }
6557 }
6558
6559 if (has_src && has_dest && can_emit_guards) {
6560 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6561 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6562 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6563 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6564
6565 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6566 // If both arrays are object arrays then having the exact types
6567 // for both will remove the need for a subtype check at runtime
6568 // before the call and may make it possible to pick a faster copy
6569 // routine (without a subtype check on every element)
6570 // Do we have the exact type of src?
6571 bool could_have_src = src_spec;
6572 // Do we have the exact type of dest?
6573 bool could_have_dest = dest_spec;
6574 ciKlass* src_k = nullptr;
6575 ciKlass* dest_k = nullptr;
6576 if (!src_spec) {
6577 src_k = src_type->speculative_type_not_null();
6578 if (src_k != nullptr && src_k->is_array_klass()) {
6579 could_have_src = true;
6580 }
6581 }
6582 if (!dest_spec) {
6583 dest_k = dest_type->speculative_type_not_null();
6584 if (dest_k != nullptr && dest_k->is_array_klass()) {
6585 could_have_dest = true;
6586 }
6587 }
6588 if (could_have_src && could_have_dest) {
6589 // If we can have both exact types, emit the missing guards
6590 if (could_have_src && !src_spec) {
6591 src = maybe_cast_profiled_obj(src, src_k, true);
6592 src_type = _gvn.type(src);
6593 top_src = src_type->isa_aryptr();
6594 }
6595 if (could_have_dest && !dest_spec) {
6596 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6597 dest_type = _gvn.type(dest);
6598 top_dest = dest_type->isa_aryptr();
6599 }
6600 }
6601 }
6602 }
6603
6604 ciMethod* trap_method = method();
6605 int trap_bci = bci();
6606 if (saved_jvms_before_guards != nullptr) {
6607 trap_method = alloc->jvms()->method();
6608 trap_bci = alloc->jvms()->bci();
6609 }
6610
6611 bool negative_length_guard_generated = false;
6612
6613 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6614 can_emit_guards && !src->is_top() && !dest->is_top()) {
6615 // validate arguments: enables transformation the ArrayCopyNode
6616 validated = true;
6617
6618 RegionNode* slow_region = new RegionNode(1);
6619 record_for_igvn(slow_region);
6620
6621 // (1) src and dest are arrays.
6622 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6623 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6624
6625 // (2) src and dest arrays must have elements of the same BasicType
6626 // done at macro expansion or at Ideal transformation time
6627
6628 // (4) src_offset must not be negative.
6629 generate_negative_guard(src_offset, slow_region);
6630
6631 // (5) dest_offset must not be negative.
6632 generate_negative_guard(dest_offset, slow_region);
6633
6634 // (7) src_offset + length must not exceed length of src.
6635 generate_limit_guard(src_offset, length,
6636 load_array_length(src),
6637 slow_region);
6638
6639 // (8) dest_offset + length must not exceed length of dest.
6640 generate_limit_guard(dest_offset, length,
6641 load_array_length(dest),
6642 slow_region);
6643
6644 // (6) length must not be negative.
6645 // This is also checked in generate_arraycopy() during macro expansion, but
6646 // we also have to check it here for the case where the ArrayCopyNode will
6647 // be eliminated by Escape Analysis.
6648 if (EliminateAllocations) {
6649 generate_negative_guard(length, slow_region);
6650 negative_length_guard_generated = true;
6651 }
6652
6653 // (9) each element of an oop array must be assignable
6654 Node* dest_klass = load_object_klass(dest);
6655 if (src != dest) {
6656 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6657 slow_region->add_req(not_subtype_ctrl);
6658 }
6659
6660 // TODO 8350865 Fix below logic. Also handle atomicity.
6661 generate_fair_guard(flat_array_test(src), slow_region);
6662 generate_fair_guard(flat_array_test(dest), slow_region);
6663
6664 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6665 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6666 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6667 src_type = _gvn.type(src);
6668 top_src = src_type->isa_aryptr();
6669
6670 // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6671 if (!stopped() && UseArrayFlattening) {
6672 // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6673 assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6674 if (top_src != nullptr && top_src->is_flat()) {
6675 // Src is flat, check that dest is flat as well
6676 if (top_dest != nullptr && !top_dest->is_flat()) {
6677 generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6678 // Since dest is flat and src <: dest, dest must have the same type as src.
6679 top_dest = top_src->cast_to_exactness(false);
6680 assert(top_dest->is_flat(), "dest must be flat");
6681 dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6682 }
6683 } else if (top_src == nullptr || !top_src->is_not_flat()) {
6684 // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6685 // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6686 assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6687 generate_fair_guard(flat_array_test(src), slow_region);
6688 if (top_src != nullptr) {
6689 top_src = top_src->cast_to_not_flat();
6690 src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6691 }
6692 }
6693 }
6694
6695 {
6696 PreserveJVMState pjvms(this);
6697 set_control(_gvn.transform(slow_region));
6698 uncommon_trap(Deoptimization::Reason_intrinsic,
6699 Deoptimization::Action_make_not_entrant);
6700 assert(stopped(), "Should be stopped");
6701 }
6702 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6703 }
6704
6705 if (stopped()) {
6706 return true;
6707 }
6708
6709 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6710 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6711 // so the compiler has a chance to eliminate them: during macro expansion,
6712 // we have to set their control (CastPP nodes are eliminated).
6713 load_object_klass(src), load_object_klass(dest),
6714 load_array_length(src), load_array_length(dest));
6715
6716 ac->set_arraycopy(validated);
6717
6718 Node* n = _gvn.transform(ac);
6719 if (n == ac) {
6720 ac->connect_outputs(this);
6721 } else {
6722 assert(validated, "shouldn't transform if all arguments not validated");
6723 set_all_memory(n);
6724 }
6725 clear_upper_avx();
6726
6727
6728 return true;
6729 }
6730
6731
6732 // Helper function which determines if an arraycopy immediately follows
6733 // an allocation, with no intervening tests or other escapes for the object.
6734 AllocateArrayNode*
6735 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6736 if (stopped()) return nullptr; // no fast path
6737 if (!C->do_aliasing()) return nullptr; // no MergeMems around
6738
6739 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6740 if (alloc == nullptr) return nullptr;
6741
6742 Node* rawmem = memory(Compile::AliasIdxRaw);
6743 // Is the allocation's memory state untouched?
6744 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6745 // Bail out if there have been raw-memory effects since the allocation.
6746 // (Example: There might have been a call or safepoint.)
6747 return nullptr;
6748 }
6749 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6750 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6751 return nullptr;
6752 }
6753
6754 // There must be no unexpected observers of this allocation.
6755 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6756 Node* obs = ptr->fast_out(i);
6757 if (obs != this->map()) {
6758 return nullptr;
6759 }
6760 }
6761
6762 // This arraycopy must unconditionally follow the allocation of the ptr.
6763 Node* alloc_ctl = ptr->in(0);
6764 Node* ctl = control();
6765 while (ctl != alloc_ctl) {
6766 // There may be guards which feed into the slow_region.
6767 // Any other control flow means that we might not get a chance
6768 // to finish initializing the allocated object.
6769 // Various low-level checks bottom out in uncommon traps. These
6770 // are considered safe since we've already checked above that
6771 // there is no unexpected observer of this allocation.
6772 if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6773 assert(ctl->in(0)->is_If(), "must be If");
6774 ctl = ctl->in(0)->in(0);
6775 } else {
6776 return nullptr;
6777 }
6778 }
6779
6780 // If we get this far, we have an allocation which immediately
6781 // precedes the arraycopy, and we can take over zeroing the new object.
6782 // The arraycopy will finish the initialization, and provide
6783 // a new control state to which we will anchor the destination pointer.
6784
6785 return alloc;
6786 }
6787
6788 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6789 if (node->is_IfProj()) {
6790 Node* other_proj = node->as_IfProj()->other_if_proj();
6791 for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6792 Node* obs = other_proj->fast_out(j);
6793 if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6794 (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6795 return obs->as_CallStaticJava();
6796 }
6797 }
6798 }
6799 return nullptr;
6800 }
6801
6802 //-------------inline_encodeISOArray-----------------------------------
6803 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6804 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6805 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6806 // encode char[] to byte[] in ISO_8859_1 or ASCII
6807 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6808 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6809 // no receiver since it is static method
6810 Node *src = argument(0);
6811 Node *src_offset = argument(1);
6812 Node *dst = argument(2);
6813 Node *dst_offset = argument(3);
6814 Node *length = argument(4);
6815
6816 // Cast source & target arrays to not-null
6817 if (VerifyIntrinsicChecks) {
6818 src = must_be_not_null(src, true);
6819 dst = must_be_not_null(dst, true);
6820 if (stopped()) {
6821 return true;
6822 }
6823 }
6824
6825 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6826 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6827 if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6828 dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6829 // failed array check
6830 return false;
6831 }
6832
6833 // Figure out the size and type of the elements we will be copying.
6834 BasicType src_elem = src_type->elem()->array_element_basic_type();
6835 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6836 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6837 return false;
6838 }
6839
6840 // Check source & target bounds
6841 if (VerifyIntrinsicChecks) {
6842 generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, true);
6843 generate_string_range_check(dst, dst_offset, length, false, true);
6844 if (stopped()) {
6845 return true;
6846 }
6847 }
6848
6849 Node* src_start = array_element_address(src, src_offset, T_CHAR);
6850 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6851 // 'src_start' points to src array + scaled offset
6852 // 'dst_start' points to dst array + scaled offset
6853
6854 const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6855 Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6856 enc = _gvn.transform(enc);
6857 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6858 set_memory(res_mem, mtype);
6859 set_result(enc);
6860 clear_upper_avx();
6861
6862 return true;
6863 }
6864
6865 //-------------inline_multiplyToLen-----------------------------------
6866 bool LibraryCallKit::inline_multiplyToLen() {
6867 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6868
6869 address stubAddr = StubRoutines::multiplyToLen();
6870 if (stubAddr == nullptr) {
6871 return false; // Intrinsic's stub is not implemented on this platform
6872 }
6873 const char* stubName = "multiplyToLen";
6874
6875 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6876
6877 // no receiver because it is a static method
6878 Node* x = argument(0);
6879 Node* xlen = argument(1);
6880 Node* y = argument(2);
6881 Node* ylen = argument(3);
6882 Node* z = argument(4);
6883
6884 x = must_be_not_null(x, true);
6885 y = must_be_not_null(y, true);
6886
6887 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6888 const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6889 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6890 y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6891 // failed array check
6892 return false;
6893 }
6894
6895 BasicType x_elem = x_type->elem()->array_element_basic_type();
6896 BasicType y_elem = y_type->elem()->array_element_basic_type();
6897 if (x_elem != T_INT || y_elem != T_INT) {
6898 return false;
6899 }
6900
6901 Node* x_start = array_element_address(x, intcon(0), x_elem);
6902 Node* y_start = array_element_address(y, intcon(0), y_elem);
6903 // 'x_start' points to x array + scaled xlen
6904 // 'y_start' points to y array + scaled ylen
6905
6906 Node* z_start = array_element_address(z, intcon(0), T_INT);
6907
6908 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6909 OptoRuntime::multiplyToLen_Type(),
6910 stubAddr, stubName, TypePtr::BOTTOM,
6911 x_start, xlen, y_start, ylen, z_start);
6912
6913 C->set_has_split_ifs(true); // Has chance for split-if optimization
6914 set_result(z);
6915 return true;
6916 }
6917
6918 //-------------inline_squareToLen------------------------------------
6919 bool LibraryCallKit::inline_squareToLen() {
6920 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6921
6922 address stubAddr = StubRoutines::squareToLen();
6923 if (stubAddr == nullptr) {
6924 return false; // Intrinsic's stub is not implemented on this platform
6925 }
6926 const char* stubName = "squareToLen";
6927
6928 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6929
6930 Node* x = argument(0);
6931 Node* len = argument(1);
6932 Node* z = argument(2);
6933 Node* zlen = argument(3);
6934
6935 x = must_be_not_null(x, true);
6936 z = must_be_not_null(z, true);
6937
6938 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6939 const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6940 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6941 z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6942 // failed array check
6943 return false;
6944 }
6945
6946 BasicType x_elem = x_type->elem()->array_element_basic_type();
6947 BasicType z_elem = z_type->elem()->array_element_basic_type();
6948 if (x_elem != T_INT || z_elem != T_INT) {
6949 return false;
6950 }
6951
6952
6953 Node* x_start = array_element_address(x, intcon(0), x_elem);
6954 Node* z_start = array_element_address(z, intcon(0), z_elem);
6955
6956 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6957 OptoRuntime::squareToLen_Type(),
6958 stubAddr, stubName, TypePtr::BOTTOM,
6959 x_start, len, z_start, zlen);
6960
6961 set_result(z);
6962 return true;
6963 }
6964
6965 //-------------inline_mulAdd------------------------------------------
6966 bool LibraryCallKit::inline_mulAdd() {
6967 assert(UseMulAddIntrinsic, "not implemented on this platform");
6968
6969 address stubAddr = StubRoutines::mulAdd();
6970 if (stubAddr == nullptr) {
6971 return false; // Intrinsic's stub is not implemented on this platform
6972 }
6973 const char* stubName = "mulAdd";
6974
6975 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6976
6977 Node* out = argument(0);
6978 Node* in = argument(1);
6979 Node* offset = argument(2);
6980 Node* len = argument(3);
6981 Node* k = argument(4);
6982
6983 in = must_be_not_null(in, true);
6984 out = must_be_not_null(out, true);
6985
6986 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6987 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6988 if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6989 in_type == nullptr || in_type->elem() == Type::BOTTOM) {
6990 // failed array check
6991 return false;
6992 }
6993
6994 BasicType out_elem = out_type->elem()->array_element_basic_type();
6995 BasicType in_elem = in_type->elem()->array_element_basic_type();
6996 if (out_elem != T_INT || in_elem != T_INT) {
6997 return false;
6998 }
6999
7000 Node* outlen = load_array_length(out);
7001 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7002 Node* out_start = array_element_address(out, intcon(0), out_elem);
7003 Node* in_start = array_element_address(in, intcon(0), in_elem);
7004
7005 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7006 OptoRuntime::mulAdd_Type(),
7007 stubAddr, stubName, TypePtr::BOTTOM,
7008 out_start,in_start, new_offset, len, k);
7009 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7010 set_result(result);
7011 return true;
7012 }
7013
7014 //-------------inline_montgomeryMultiply-----------------------------------
7015 bool LibraryCallKit::inline_montgomeryMultiply() {
7016 address stubAddr = StubRoutines::montgomeryMultiply();
7017 if (stubAddr == nullptr) {
7018 return false; // Intrinsic's stub is not implemented on this platform
7019 }
7020
7021 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7022 const char* stubName = "montgomery_multiply";
7023
7024 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7025
7026 Node* a = argument(0);
7027 Node* b = argument(1);
7028 Node* n = argument(2);
7029 Node* len = argument(3);
7030 Node* inv = argument(4);
7031 Node* m = argument(6);
7032
7033 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7034 const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7035 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7036 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7037 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7038 b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7039 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7040 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7041 // failed array check
7042 return false;
7043 }
7044
7045 BasicType a_elem = a_type->elem()->array_element_basic_type();
7046 BasicType b_elem = b_type->elem()->array_element_basic_type();
7047 BasicType n_elem = n_type->elem()->array_element_basic_type();
7048 BasicType m_elem = m_type->elem()->array_element_basic_type();
7049 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7050 return false;
7051 }
7052
7053 // Make the call
7054 {
7055 Node* a_start = array_element_address(a, intcon(0), a_elem);
7056 Node* b_start = array_element_address(b, intcon(0), b_elem);
7057 Node* n_start = array_element_address(n, intcon(0), n_elem);
7058 Node* m_start = array_element_address(m, intcon(0), m_elem);
7059
7060 Node* call = make_runtime_call(RC_LEAF,
7061 OptoRuntime::montgomeryMultiply_Type(),
7062 stubAddr, stubName, TypePtr::BOTTOM,
7063 a_start, b_start, n_start, len, inv, top(),
7064 m_start);
7065 set_result(m);
7066 }
7067
7068 return true;
7069 }
7070
7071 bool LibraryCallKit::inline_montgomerySquare() {
7072 address stubAddr = StubRoutines::montgomerySquare();
7073 if (stubAddr == nullptr) {
7074 return false; // Intrinsic's stub is not implemented on this platform
7075 }
7076
7077 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7078 const char* stubName = "montgomery_square";
7079
7080 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7081
7082 Node* a = argument(0);
7083 Node* n = argument(1);
7084 Node* len = argument(2);
7085 Node* inv = argument(3);
7086 Node* m = argument(5);
7087
7088 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7089 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7090 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7091 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7092 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7093 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7094 // failed array check
7095 return false;
7096 }
7097
7098 BasicType a_elem = a_type->elem()->array_element_basic_type();
7099 BasicType n_elem = n_type->elem()->array_element_basic_type();
7100 BasicType m_elem = m_type->elem()->array_element_basic_type();
7101 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7102 return false;
7103 }
7104
7105 // Make the call
7106 {
7107 Node* a_start = array_element_address(a, intcon(0), a_elem);
7108 Node* n_start = array_element_address(n, intcon(0), n_elem);
7109 Node* m_start = array_element_address(m, intcon(0), m_elem);
7110
7111 Node* call = make_runtime_call(RC_LEAF,
7112 OptoRuntime::montgomerySquare_Type(),
7113 stubAddr, stubName, TypePtr::BOTTOM,
7114 a_start, n_start, len, inv, top(),
7115 m_start);
7116 set_result(m);
7117 }
7118
7119 return true;
7120 }
7121
7122 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7123 address stubAddr = nullptr;
7124 const char* stubName = nullptr;
7125
7126 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7127 if (stubAddr == nullptr) {
7128 return false; // Intrinsic's stub is not implemented on this platform
7129 }
7130
7131 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7132
7133 assert(callee()->signature()->size() == 5, "expected 5 arguments");
7134
7135 Node* newArr = argument(0);
7136 Node* oldArr = argument(1);
7137 Node* newIdx = argument(2);
7138 Node* shiftCount = argument(3);
7139 Node* numIter = argument(4);
7140
7141 const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7142 const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7143 if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7144 oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7145 return false;
7146 }
7147
7148 BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7149 BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7150 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7151 return false;
7152 }
7153
7154 // Make the call
7155 {
7156 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7157 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7158
7159 Node* call = make_runtime_call(RC_LEAF,
7160 OptoRuntime::bigIntegerShift_Type(),
7161 stubAddr,
7162 stubName,
7163 TypePtr::BOTTOM,
7164 newArr_start,
7165 oldArr_start,
7166 newIdx,
7167 shiftCount,
7168 numIter);
7169 }
7170
7171 return true;
7172 }
7173
7174 //-------------inline_vectorizedMismatch------------------------------
7175 bool LibraryCallKit::inline_vectorizedMismatch() {
7176 assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7177
7178 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7179 Node* obja = argument(0); // Object
7180 Node* aoffset = argument(1); // long
7181 Node* objb = argument(3); // Object
7182 Node* boffset = argument(4); // long
7183 Node* length = argument(6); // int
7184 Node* scale = argument(7); // int
7185
7186 const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7187 const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7188 if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7189 objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7190 scale == top()) {
7191 return false; // failed input validation
7192 }
7193
7194 Node* obja_adr = make_unsafe_address(obja, aoffset);
7195 Node* objb_adr = make_unsafe_address(objb, boffset);
7196
7197 // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7198 //
7199 // inline_limit = ArrayOperationPartialInlineSize / element_size;
7200 // if (length <= inline_limit) {
7201 // inline_path:
7202 // vmask = VectorMaskGen length
7203 // vload1 = LoadVectorMasked obja, vmask
7204 // vload2 = LoadVectorMasked objb, vmask
7205 // result1 = VectorCmpMasked vload1, vload2, vmask
7206 // } else {
7207 // call_stub_path:
7208 // result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7209 // }
7210 // exit_block:
7211 // return Phi(result1, result2);
7212 //
7213 enum { inline_path = 1, // input is small enough to process it all at once
7214 stub_path = 2, // input is too large; call into the VM
7215 PATH_LIMIT = 3
7216 };
7217
7218 Node* exit_block = new RegionNode(PATH_LIMIT);
7219 Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7220 Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7221
7222 Node* call_stub_path = control();
7223
7224 BasicType elem_bt = T_ILLEGAL;
7225
7226 const TypeInt* scale_t = _gvn.type(scale)->is_int();
7227 if (scale_t->is_con()) {
7228 switch (scale_t->get_con()) {
7229 case 0: elem_bt = T_BYTE; break;
7230 case 1: elem_bt = T_SHORT; break;
7231 case 2: elem_bt = T_INT; break;
7232 case 3: elem_bt = T_LONG; break;
7233
7234 default: elem_bt = T_ILLEGAL; break; // not supported
7235 }
7236 }
7237
7238 int inline_limit = 0;
7239 bool do_partial_inline = false;
7240
7241 if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7242 inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7243 do_partial_inline = inline_limit >= 16;
7244 }
7245
7246 if (do_partial_inline) {
7247 assert(elem_bt != T_ILLEGAL, "sanity");
7248
7249 if (Matcher::match_rule_supported_vector(Op_VectorMaskGen, inline_limit, elem_bt) &&
7250 Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7251 Matcher::match_rule_supported_vector(Op_VectorCmpMasked, inline_limit, elem_bt)) {
7252
7253 const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7254 Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7255 Node* bol_gt = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7256
7257 call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7258
7259 if (!stopped()) {
7260 Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7261
7262 const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7263 const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7264 Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7265 Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7266
7267 Node* vmask = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7268 Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7269 Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7270 Node* result = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7271
7272 exit_block->init_req(inline_path, control());
7273 memory_phi->init_req(inline_path, map()->memory());
7274 result_phi->init_req(inline_path, result);
7275
7276 C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7277 clear_upper_avx();
7278 }
7279 }
7280 }
7281
7282 if (call_stub_path != nullptr) {
7283 set_control(call_stub_path);
7284
7285 Node* call = make_runtime_call(RC_LEAF,
7286 OptoRuntime::vectorizedMismatch_Type(),
7287 StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7288 obja_adr, objb_adr, length, scale);
7289
7290 exit_block->init_req(stub_path, control());
7291 memory_phi->init_req(stub_path, map()->memory());
7292 result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7293 }
7294
7295 exit_block = _gvn.transform(exit_block);
7296 memory_phi = _gvn.transform(memory_phi);
7297 result_phi = _gvn.transform(result_phi);
7298
7299 record_for_igvn(exit_block);
7300 record_for_igvn(memory_phi);
7301 record_for_igvn(result_phi);
7302
7303 set_control(exit_block);
7304 set_all_memory(memory_phi);
7305 set_result(result_phi);
7306
7307 return true;
7308 }
7309
7310 //------------------------------inline_vectorizedHashcode----------------------------
7311 bool LibraryCallKit::inline_vectorizedHashCode() {
7312 assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7313
7314 assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7315 Node* array = argument(0);
7316 Node* offset = argument(1);
7317 Node* length = argument(2);
7318 Node* initialValue = argument(3);
7319 Node* basic_type = argument(4);
7320
7321 if (basic_type == top()) {
7322 return false; // failed input validation
7323 }
7324
7325 const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7326 if (!basic_type_t->is_con()) {
7327 return false; // Only intrinsify if mode argument is constant
7328 }
7329
7330 array = must_be_not_null(array, true);
7331
7332 BasicType bt = (BasicType)basic_type_t->get_con();
7333
7334 // Resolve address of first element
7335 Node* array_start = array_element_address(array, offset, bt);
7336
7337 set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7338 array_start, length, initialValue, basic_type)));
7339 clear_upper_avx();
7340
7341 return true;
7342 }
7343
7344 /**
7345 * Calculate CRC32 for byte.
7346 * int java.util.zip.CRC32.update(int crc, int b)
7347 */
7348 bool LibraryCallKit::inline_updateCRC32() {
7349 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7350 assert(callee()->signature()->size() == 2, "update has 2 parameters");
7351 // no receiver since it is static method
7352 Node* crc = argument(0); // type: int
7353 Node* b = argument(1); // type: int
7354
7355 /*
7356 * int c = ~ crc;
7357 * b = timesXtoThe32[(b ^ c) & 0xFF];
7358 * b = b ^ (c >>> 8);
7359 * crc = ~b;
7360 */
7361
7362 Node* M1 = intcon(-1);
7363 crc = _gvn.transform(new XorINode(crc, M1));
7364 Node* result = _gvn.transform(new XorINode(crc, b));
7365 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7366
7367 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7368 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7369 Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7370 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7371
7372 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7373 result = _gvn.transform(new XorINode(crc, result));
7374 result = _gvn.transform(new XorINode(result, M1));
7375 set_result(result);
7376 return true;
7377 }
7378
7379 /**
7380 * Calculate CRC32 for byte[] array.
7381 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7382 */
7383 bool LibraryCallKit::inline_updateBytesCRC32() {
7384 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7385 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7386 // no receiver since it is static method
7387 Node* crc = argument(0); // type: int
7388 Node* src = argument(1); // type: oop
7389 Node* offset = argument(2); // type: int
7390 Node* length = argument(3); // type: int
7391
7392 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7393 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7394 // failed array check
7395 return false;
7396 }
7397
7398 // Figure out the size and type of the elements we will be copying.
7399 BasicType src_elem = src_type->elem()->array_element_basic_type();
7400 if (src_elem != T_BYTE) {
7401 return false;
7402 }
7403
7404 // 'src_start' points to src array + scaled offset
7405 src = must_be_not_null(src, true);
7406 Node* src_start = array_element_address(src, offset, src_elem);
7407
7408 // We assume that range check is done by caller.
7409 // TODO: generate range check (offset+length < src.length) in debug VM.
7410
7411 // Call the stub.
7412 address stubAddr = StubRoutines::updateBytesCRC32();
7413 const char *stubName = "updateBytesCRC32";
7414
7415 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7416 stubAddr, stubName, TypePtr::BOTTOM,
7417 crc, src_start, length);
7418 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7419 set_result(result);
7420 return true;
7421 }
7422
7423 /**
7424 * Calculate CRC32 for ByteBuffer.
7425 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7426 */
7427 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7428 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7429 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7430 // no receiver since it is static method
7431 Node* crc = argument(0); // type: int
7432 Node* src = argument(1); // type: long
7433 Node* offset = argument(3); // type: int
7434 Node* length = argument(4); // type: int
7435
7436 src = ConvL2X(src); // adjust Java long to machine word
7437 Node* base = _gvn.transform(new CastX2PNode(src));
7438 offset = ConvI2X(offset);
7439
7440 // 'src_start' points to src array + scaled offset
7441 Node* src_start = basic_plus_adr(top(), base, offset);
7442
7443 // Call the stub.
7444 address stubAddr = StubRoutines::updateBytesCRC32();
7445 const char *stubName = "updateBytesCRC32";
7446
7447 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7448 stubAddr, stubName, TypePtr::BOTTOM,
7449 crc, src_start, length);
7450 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7451 set_result(result);
7452 return true;
7453 }
7454
7455 //------------------------------get_table_from_crc32c_class-----------------------
7456 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7457 Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7458 assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7459
7460 return table;
7461 }
7462
7463 //------------------------------inline_updateBytesCRC32C-----------------------
7464 //
7465 // Calculate CRC32C for byte[] array.
7466 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7467 //
7468 bool LibraryCallKit::inline_updateBytesCRC32C() {
7469 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7470 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7471 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7472 // no receiver since it is a static method
7473 Node* crc = argument(0); // type: int
7474 Node* src = argument(1); // type: oop
7475 Node* offset = argument(2); // type: int
7476 Node* end = argument(3); // type: int
7477
7478 Node* length = _gvn.transform(new SubINode(end, offset));
7479
7480 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7481 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7482 // failed array check
7483 return false;
7484 }
7485
7486 // Figure out the size and type of the elements we will be copying.
7487 BasicType src_elem = src_type->elem()->array_element_basic_type();
7488 if (src_elem != T_BYTE) {
7489 return false;
7490 }
7491
7492 // 'src_start' points to src array + scaled offset
7493 src = must_be_not_null(src, true);
7494 Node* src_start = array_element_address(src, offset, src_elem);
7495
7496 // static final int[] byteTable in class CRC32C
7497 Node* table = get_table_from_crc32c_class(callee()->holder());
7498 table = must_be_not_null(table, true);
7499 Node* table_start = array_element_address(table, intcon(0), T_INT);
7500
7501 // We assume that range check is done by caller.
7502 // TODO: generate range check (offset+length < src.length) in debug VM.
7503
7504 // Call the stub.
7505 address stubAddr = StubRoutines::updateBytesCRC32C();
7506 const char *stubName = "updateBytesCRC32C";
7507
7508 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7509 stubAddr, stubName, TypePtr::BOTTOM,
7510 crc, src_start, length, table_start);
7511 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7512 set_result(result);
7513 return true;
7514 }
7515
7516 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7517 //
7518 // Calculate CRC32C for DirectByteBuffer.
7519 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7520 //
7521 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7522 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7523 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7524 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7525 // no receiver since it is a static method
7526 Node* crc = argument(0); // type: int
7527 Node* src = argument(1); // type: long
7528 Node* offset = argument(3); // type: int
7529 Node* end = argument(4); // type: int
7530
7531 Node* length = _gvn.transform(new SubINode(end, offset));
7532
7533 src = ConvL2X(src); // adjust Java long to machine word
7534 Node* base = _gvn.transform(new CastX2PNode(src));
7535 offset = ConvI2X(offset);
7536
7537 // 'src_start' points to src array + scaled offset
7538 Node* src_start = basic_plus_adr(top(), base, offset);
7539
7540 // static final int[] byteTable in class CRC32C
7541 Node* table = get_table_from_crc32c_class(callee()->holder());
7542 table = must_be_not_null(table, true);
7543 Node* table_start = array_element_address(table, intcon(0), T_INT);
7544
7545 // Call the stub.
7546 address stubAddr = StubRoutines::updateBytesCRC32C();
7547 const char *stubName = "updateBytesCRC32C";
7548
7549 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7550 stubAddr, stubName, TypePtr::BOTTOM,
7551 crc, src_start, length, table_start);
7552 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7553 set_result(result);
7554 return true;
7555 }
7556
7557 //------------------------------inline_updateBytesAdler32----------------------
7558 //
7559 // Calculate Adler32 checksum for byte[] array.
7560 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7561 //
7562 bool LibraryCallKit::inline_updateBytesAdler32() {
7563 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7564 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7565 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7566 // no receiver since it is static method
7567 Node* crc = argument(0); // type: int
7568 Node* src = argument(1); // type: oop
7569 Node* offset = argument(2); // type: int
7570 Node* length = argument(3); // type: int
7571
7572 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7573 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7574 // failed array check
7575 return false;
7576 }
7577
7578 // Figure out the size and type of the elements we will be copying.
7579 BasicType src_elem = src_type->elem()->array_element_basic_type();
7580 if (src_elem != T_BYTE) {
7581 return false;
7582 }
7583
7584 // 'src_start' points to src array + scaled offset
7585 Node* src_start = array_element_address(src, offset, src_elem);
7586
7587 // We assume that range check is done by caller.
7588 // TODO: generate range check (offset+length < src.length) in debug VM.
7589
7590 // Call the stub.
7591 address stubAddr = StubRoutines::updateBytesAdler32();
7592 const char *stubName = "updateBytesAdler32";
7593
7594 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7595 stubAddr, stubName, TypePtr::BOTTOM,
7596 crc, src_start, length);
7597 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7598 set_result(result);
7599 return true;
7600 }
7601
7602 //------------------------------inline_updateByteBufferAdler32---------------
7603 //
7604 // Calculate Adler32 checksum for DirectByteBuffer.
7605 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7606 //
7607 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7608 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7609 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7610 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7611 // no receiver since it is static method
7612 Node* crc = argument(0); // type: int
7613 Node* src = argument(1); // type: long
7614 Node* offset = argument(3); // type: int
7615 Node* length = argument(4); // type: int
7616
7617 src = ConvL2X(src); // adjust Java long to machine word
7618 Node* base = _gvn.transform(new CastX2PNode(src));
7619 offset = ConvI2X(offset);
7620
7621 // 'src_start' points to src array + scaled offset
7622 Node* src_start = basic_plus_adr(top(), base, offset);
7623
7624 // Call the stub.
7625 address stubAddr = StubRoutines::updateBytesAdler32();
7626 const char *stubName = "updateBytesAdler32";
7627
7628 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7629 stubAddr, stubName, TypePtr::BOTTOM,
7630 crc, src_start, length);
7631
7632 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7633 set_result(result);
7634 return true;
7635 }
7636
7637 //----------------------------inline_reference_get0----------------------------
7638 // public T java.lang.ref.Reference.get();
7639 bool LibraryCallKit::inline_reference_get0() {
7640 const int referent_offset = java_lang_ref_Reference::referent_offset();
7641
7642 // Get the argument:
7643 Node* reference_obj = null_check_receiver();
7644 if (stopped()) return true;
7645
7646 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7647 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7648 decorators, /*is_static*/ false, nullptr);
7649 if (result == nullptr) return false;
7650
7651 // Add memory barrier to prevent commoning reads from this field
7652 // across safepoint since GC can change its value.
7653 insert_mem_bar(Op_MemBarCPUOrder);
7654
7655 set_result(result);
7656 return true;
7657 }
7658
7659 //----------------------------inline_reference_refersTo0----------------------------
7660 // bool java.lang.ref.Reference.refersTo0();
7661 // bool java.lang.ref.PhantomReference.refersTo0();
7662 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7663 // Get arguments:
7664 Node* reference_obj = null_check_receiver();
7665 Node* other_obj = argument(1);
7666 if (stopped()) return true;
7667
7668 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7669 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7670 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7671 decorators, /*is_static*/ false, nullptr);
7672 if (referent == nullptr) return false;
7673
7674 // Add memory barrier to prevent commoning reads from this field
7675 // across safepoint since GC can change its value.
7676 insert_mem_bar(Op_MemBarCPUOrder);
7677
7678 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7679 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7680 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7681
7682 RegionNode* region = new RegionNode(3);
7683 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7684
7685 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7686 region->init_req(1, if_true);
7687 phi->init_req(1, intcon(1));
7688
7689 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7690 region->init_req(2, if_false);
7691 phi->init_req(2, intcon(0));
7692
7693 set_control(_gvn.transform(region));
7694 record_for_igvn(region);
7695 set_result(_gvn.transform(phi));
7696 return true;
7697 }
7698
7699 //----------------------------inline_reference_clear0----------------------------
7700 // void java.lang.ref.Reference.clear0();
7701 // void java.lang.ref.PhantomReference.clear0();
7702 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7703 // This matches the implementation in JVM_ReferenceClear, see the comments there.
7704
7705 // Get arguments
7706 Node* reference_obj = null_check_receiver();
7707 if (stopped()) return true;
7708
7709 // Common access parameters
7710 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7711 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7712 Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7713 const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7714 const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7715
7716 Node* referent = access_load_at(reference_obj,
7717 referent_field_addr,
7718 referent_field_addr_type,
7719 val_type,
7720 T_OBJECT,
7721 decorators);
7722
7723 IdealKit ideal(this);
7724 #define __ ideal.
7725 __ if_then(referent, BoolTest::ne, null());
7726 sync_kit(ideal);
7727 access_store_at(reference_obj,
7728 referent_field_addr,
7729 referent_field_addr_type,
7730 null(),
7731 val_type,
7732 T_OBJECT,
7733 decorators);
7734 __ sync_kit(this);
7735 __ end_if();
7736 final_sync(ideal);
7737 #undef __
7738
7739 return true;
7740 }
7741
7742 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7743 DecoratorSet decorators, bool is_static,
7744 ciInstanceKlass* fromKls) {
7745 if (fromKls == nullptr) {
7746 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7747 assert(tinst != nullptr, "obj is null");
7748 assert(tinst->is_loaded(), "obj is not loaded");
7749 fromKls = tinst->instance_klass();
7750 } else {
7751 assert(is_static, "only for static field access");
7752 }
7753 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7754 ciSymbol::make(fieldTypeString),
7755 is_static);
7756
7757 assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7758 if (field == nullptr) return (Node *) nullptr;
7759
7760 if (is_static) {
7761 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7762 fromObj = makecon(tip);
7763 }
7764
7765 // Next code copied from Parse::do_get_xxx():
7766
7767 // Compute address and memory type.
7768 int offset = field->offset_in_bytes();
7769 bool is_vol = field->is_volatile();
7770 ciType* field_klass = field->type();
7771 assert(field_klass->is_loaded(), "should be loaded");
7772 const TypePtr* adr_type = C->alias_type(field)->adr_type();
7773 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7774 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7775 "slice of address and input slice don't match");
7776 BasicType bt = field->layout_type();
7777
7778 // Build the resultant type of the load
7779 const Type *type;
7780 if (bt == T_OBJECT) {
7781 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7782 } else {
7783 type = Type::get_const_basic_type(bt);
7784 }
7785
7786 if (is_vol) {
7787 decorators |= MO_SEQ_CST;
7788 }
7789
7790 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7791 }
7792
7793 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7794 bool is_exact /* true */, bool is_static /* false */,
7795 ciInstanceKlass * fromKls /* nullptr */) {
7796 if (fromKls == nullptr) {
7797 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7798 assert(tinst != nullptr, "obj is null");
7799 assert(tinst->is_loaded(), "obj is not loaded");
7800 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7801 fromKls = tinst->instance_klass();
7802 }
7803 else {
7804 assert(is_static, "only for static field access");
7805 }
7806 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7807 ciSymbol::make(fieldTypeString),
7808 is_static);
7809
7810 assert(field != nullptr, "undefined field");
7811 assert(!field->is_volatile(), "not defined for volatile fields");
7812
7813 if (is_static) {
7814 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7815 fromObj = makecon(tip);
7816 }
7817
7818 // Next code copied from Parse::do_get_xxx():
7819
7820 // Compute address and memory type.
7821 int offset = field->offset_in_bytes();
7822 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7823
7824 return adr;
7825 }
7826
7827 //------------------------------inline_aescrypt_Block-----------------------
7828 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7829 address stubAddr = nullptr;
7830 const char *stubName;
7831 assert(UseAES, "need AES instruction support");
7832
7833 switch(id) {
7834 case vmIntrinsics::_aescrypt_encryptBlock:
7835 stubAddr = StubRoutines::aescrypt_encryptBlock();
7836 stubName = "aescrypt_encryptBlock";
7837 break;
7838 case vmIntrinsics::_aescrypt_decryptBlock:
7839 stubAddr = StubRoutines::aescrypt_decryptBlock();
7840 stubName = "aescrypt_decryptBlock";
7841 break;
7842 default:
7843 break;
7844 }
7845 if (stubAddr == nullptr) return false;
7846
7847 Node* aescrypt_object = argument(0);
7848 Node* src = argument(1);
7849 Node* src_offset = argument(2);
7850 Node* dest = argument(3);
7851 Node* dest_offset = argument(4);
7852
7853 src = must_be_not_null(src, true);
7854 dest = must_be_not_null(dest, true);
7855
7856 // (1) src and dest are arrays.
7857 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7858 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7859 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7860 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7861
7862 // for the quick and dirty code we will skip all the checks.
7863 // we are just trying to get the call to be generated.
7864 Node* src_start = src;
7865 Node* dest_start = dest;
7866 if (src_offset != nullptr || dest_offset != nullptr) {
7867 assert(src_offset != nullptr && dest_offset != nullptr, "");
7868 src_start = array_element_address(src, src_offset, T_BYTE);
7869 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7870 }
7871
7872 // now need to get the start of its expanded key array
7873 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7874 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7875 if (k_start == nullptr) return false;
7876
7877 // Call the stub.
7878 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7879 stubAddr, stubName, TypePtr::BOTTOM,
7880 src_start, dest_start, k_start);
7881
7882 return true;
7883 }
7884
7885 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7886 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7887 address stubAddr = nullptr;
7888 const char *stubName = nullptr;
7889
7890 assert(UseAES, "need AES instruction support");
7891
7892 switch(id) {
7893 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7894 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7895 stubName = "cipherBlockChaining_encryptAESCrypt";
7896 break;
7897 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7898 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7899 stubName = "cipherBlockChaining_decryptAESCrypt";
7900 break;
7901 default:
7902 break;
7903 }
7904 if (stubAddr == nullptr) return false;
7905
7906 Node* cipherBlockChaining_object = argument(0);
7907 Node* src = argument(1);
7908 Node* src_offset = argument(2);
7909 Node* len = argument(3);
7910 Node* dest = argument(4);
7911 Node* dest_offset = argument(5);
7912
7913 src = must_be_not_null(src, false);
7914 dest = must_be_not_null(dest, false);
7915
7916 // (1) src and dest are arrays.
7917 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7918 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7919 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7920 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7921
7922 // checks are the responsibility of the caller
7923 Node* src_start = src;
7924 Node* dest_start = dest;
7925 if (src_offset != nullptr || dest_offset != nullptr) {
7926 assert(src_offset != nullptr && dest_offset != nullptr, "");
7927 src_start = array_element_address(src, src_offset, T_BYTE);
7928 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7929 }
7930
7931 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7932 // (because of the predicated logic executed earlier).
7933 // so we cast it here safely.
7934 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7935
7936 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7937 if (embeddedCipherObj == nullptr) return false;
7938
7939 // cast it to what we know it will be at runtime
7940 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7941 assert(tinst != nullptr, "CBC obj is null");
7942 assert(tinst->is_loaded(), "CBC obj is not loaded");
7943 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7944 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7945
7946 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7947 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7948 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7949 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7950 aescrypt_object = _gvn.transform(aescrypt_object);
7951
7952 // we need to get the start of the aescrypt_object's expanded key array
7953 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7954 if (k_start == nullptr) return false;
7955
7956 // similarly, get the start address of the r vector
7957 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7958 if (objRvec == nullptr) return false;
7959 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7960
7961 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7962 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7963 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7964 stubAddr, stubName, TypePtr::BOTTOM,
7965 src_start, dest_start, k_start, r_start, len);
7966
7967 // return cipher length (int)
7968 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7969 set_result(retvalue);
7970 return true;
7971 }
7972
7973 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7974 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7975 address stubAddr = nullptr;
7976 const char *stubName = nullptr;
7977
7978 assert(UseAES, "need AES instruction support");
7979
7980 switch (id) {
7981 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7982 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7983 stubName = "electronicCodeBook_encryptAESCrypt";
7984 break;
7985 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7986 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7987 stubName = "electronicCodeBook_decryptAESCrypt";
7988 break;
7989 default:
7990 break;
7991 }
7992
7993 if (stubAddr == nullptr) return false;
7994
7995 Node* electronicCodeBook_object = argument(0);
7996 Node* src = argument(1);
7997 Node* src_offset = argument(2);
7998 Node* len = argument(3);
7999 Node* dest = argument(4);
8000 Node* dest_offset = argument(5);
8001
8002 // (1) src and dest are arrays.
8003 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8004 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8005 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8006 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8007
8008 // checks are the responsibility of the caller
8009 Node* src_start = src;
8010 Node* dest_start = dest;
8011 if (src_offset != nullptr || dest_offset != nullptr) {
8012 assert(src_offset != nullptr && dest_offset != nullptr, "");
8013 src_start = array_element_address(src, src_offset, T_BYTE);
8014 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8015 }
8016
8017 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8018 // (because of the predicated logic executed earlier).
8019 // so we cast it here safely.
8020 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8021
8022 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8023 if (embeddedCipherObj == nullptr) return false;
8024
8025 // cast it to what we know it will be at runtime
8026 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8027 assert(tinst != nullptr, "ECB obj is null");
8028 assert(tinst->is_loaded(), "ECB obj is not loaded");
8029 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8030 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8031
8032 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8033 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8034 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8035 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8036 aescrypt_object = _gvn.transform(aescrypt_object);
8037
8038 // we need to get the start of the aescrypt_object's expanded key array
8039 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8040 if (k_start == nullptr) return false;
8041
8042 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8043 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8044 OptoRuntime::electronicCodeBook_aescrypt_Type(),
8045 stubAddr, stubName, TypePtr::BOTTOM,
8046 src_start, dest_start, k_start, len);
8047
8048 // return cipher length (int)
8049 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8050 set_result(retvalue);
8051 return true;
8052 }
8053
8054 //------------------------------inline_counterMode_AESCrypt-----------------------
8055 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8056 assert(UseAES, "need AES instruction support");
8057 if (!UseAESCTRIntrinsics) return false;
8058
8059 address stubAddr = nullptr;
8060 const char *stubName = nullptr;
8061 if (id == vmIntrinsics::_counterMode_AESCrypt) {
8062 stubAddr = StubRoutines::counterMode_AESCrypt();
8063 stubName = "counterMode_AESCrypt";
8064 }
8065 if (stubAddr == nullptr) return false;
8066
8067 Node* counterMode_object = argument(0);
8068 Node* src = argument(1);
8069 Node* src_offset = argument(2);
8070 Node* len = argument(3);
8071 Node* dest = argument(4);
8072 Node* dest_offset = argument(5);
8073
8074 // (1) src and dest are arrays.
8075 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8076 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8077 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8078 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8079
8080 // checks are the responsibility of the caller
8081 Node* src_start = src;
8082 Node* dest_start = dest;
8083 if (src_offset != nullptr || dest_offset != nullptr) {
8084 assert(src_offset != nullptr && dest_offset != nullptr, "");
8085 src_start = array_element_address(src, src_offset, T_BYTE);
8086 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8087 }
8088
8089 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8090 // (because of the predicated logic executed earlier).
8091 // so we cast it here safely.
8092 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8093 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8094 if (embeddedCipherObj == nullptr) return false;
8095 // cast it to what we know it will be at runtime
8096 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8097 assert(tinst != nullptr, "CTR obj is null");
8098 assert(tinst->is_loaded(), "CTR obj is not loaded");
8099 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8100 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8101 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8102 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8103 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8104 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8105 aescrypt_object = _gvn.transform(aescrypt_object);
8106 // we need to get the start of the aescrypt_object's expanded key array
8107 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8108 if (k_start == nullptr) return false;
8109 // similarly, get the start address of the r vector
8110 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8111 if (obj_counter == nullptr) return false;
8112 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8113
8114 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8115 if (saved_encCounter == nullptr) return false;
8116 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8117 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8118
8119 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8120 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8121 OptoRuntime::counterMode_aescrypt_Type(),
8122 stubAddr, stubName, TypePtr::BOTTOM,
8123 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8124
8125 // return cipher length (int)
8126 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8127 set_result(retvalue);
8128 return true;
8129 }
8130
8131 //------------------------------get_key_start_from_aescrypt_object-----------------------
8132 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
8133 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8134 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8135 // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8136 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8137 // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
8138 Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
8139 assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
8140 if (objSessionK == nullptr) {
8141 return (Node *) nullptr;
8142 }
8143 Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
8144 #else
8145 Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
8146 #endif // PPC64
8147 assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
8148 if (objAESCryptKey == nullptr) return (Node *) nullptr;
8149
8150 // now have the array, need to get the start address of the K array
8151 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8152 return k_start;
8153 }
8154
8155 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8156 // Return node representing slow path of predicate check.
8157 // the pseudo code we want to emulate with this predicate is:
8158 // for encryption:
8159 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8160 // for decryption:
8161 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8162 // note cipher==plain is more conservative than the original java code but that's OK
8163 //
8164 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8165 // The receiver was checked for null already.
8166 Node* objCBC = argument(0);
8167
8168 Node* src = argument(1);
8169 Node* dest = argument(4);
8170
8171 // Load embeddedCipher field of CipherBlockChaining object.
8172 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8173
8174 // get AESCrypt klass for instanceOf check
8175 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8176 // will have same classloader as CipherBlockChaining object
8177 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8178 assert(tinst != nullptr, "CBCobj is null");
8179 assert(tinst->is_loaded(), "CBCobj is not loaded");
8180
8181 // we want to do an instanceof comparison against the AESCrypt class
8182 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8183 if (!klass_AESCrypt->is_loaded()) {
8184 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8185 Node* ctrl = control();
8186 set_control(top()); // no regular fast path
8187 return ctrl;
8188 }
8189
8190 src = must_be_not_null(src, true);
8191 dest = must_be_not_null(dest, true);
8192
8193 // Resolve oops to stable for CmpP below.
8194 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8195
8196 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8197 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8198 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8199
8200 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8201
8202 // for encryption, we are done
8203 if (!decrypting)
8204 return instof_false; // even if it is null
8205
8206 // for decryption, we need to add a further check to avoid
8207 // taking the intrinsic path when cipher and plain are the same
8208 // see the original java code for why.
8209 RegionNode* region = new RegionNode(3);
8210 region->init_req(1, instof_false);
8211
8212 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8213 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8214 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8215 region->init_req(2, src_dest_conjoint);
8216
8217 record_for_igvn(region);
8218 return _gvn.transform(region);
8219 }
8220
8221 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8222 // Return node representing slow path of predicate check.
8223 // the pseudo code we want to emulate with this predicate is:
8224 // for encryption:
8225 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8226 // for decryption:
8227 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8228 // note cipher==plain is more conservative than the original java code but that's OK
8229 //
8230 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8231 // The receiver was checked for null already.
8232 Node* objECB = argument(0);
8233
8234 // Load embeddedCipher field of ElectronicCodeBook object.
8235 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8236
8237 // get AESCrypt klass for instanceOf check
8238 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8239 // will have same classloader as ElectronicCodeBook object
8240 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8241 assert(tinst != nullptr, "ECBobj is null");
8242 assert(tinst->is_loaded(), "ECBobj is not loaded");
8243
8244 // we want to do an instanceof comparison against the AESCrypt class
8245 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8246 if (!klass_AESCrypt->is_loaded()) {
8247 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8248 Node* ctrl = control();
8249 set_control(top()); // no regular fast path
8250 return ctrl;
8251 }
8252 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8253
8254 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8255 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8256 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8257
8258 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8259
8260 // for encryption, we are done
8261 if (!decrypting)
8262 return instof_false; // even if it is null
8263
8264 // for decryption, we need to add a further check to avoid
8265 // taking the intrinsic path when cipher and plain are the same
8266 // see the original java code for why.
8267 RegionNode* region = new RegionNode(3);
8268 region->init_req(1, instof_false);
8269 Node* src = argument(1);
8270 Node* dest = argument(4);
8271 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8272 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8273 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8274 region->init_req(2, src_dest_conjoint);
8275
8276 record_for_igvn(region);
8277 return _gvn.transform(region);
8278 }
8279
8280 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8281 // Return node representing slow path of predicate check.
8282 // the pseudo code we want to emulate with this predicate is:
8283 // for encryption:
8284 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8285 // for decryption:
8286 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8287 // note cipher==plain is more conservative than the original java code but that's OK
8288 //
8289
8290 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8291 // The receiver was checked for null already.
8292 Node* objCTR = argument(0);
8293
8294 // Load embeddedCipher field of CipherBlockChaining object.
8295 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8296
8297 // get AESCrypt klass for instanceOf check
8298 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8299 // will have same classloader as CipherBlockChaining object
8300 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8301 assert(tinst != nullptr, "CTRobj is null");
8302 assert(tinst->is_loaded(), "CTRobj is not loaded");
8303
8304 // we want to do an instanceof comparison against the AESCrypt class
8305 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8306 if (!klass_AESCrypt->is_loaded()) {
8307 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8308 Node* ctrl = control();
8309 set_control(top()); // no regular fast path
8310 return ctrl;
8311 }
8312
8313 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8314 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8315 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8316 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8317 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8318
8319 return instof_false; // even if it is null
8320 }
8321
8322 //------------------------------inline_ghash_processBlocks
8323 bool LibraryCallKit::inline_ghash_processBlocks() {
8324 address stubAddr;
8325 const char *stubName;
8326 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8327
8328 stubAddr = StubRoutines::ghash_processBlocks();
8329 stubName = "ghash_processBlocks";
8330
8331 Node* data = argument(0);
8332 Node* offset = argument(1);
8333 Node* len = argument(2);
8334 Node* state = argument(3);
8335 Node* subkeyH = argument(4);
8336
8337 state = must_be_not_null(state, true);
8338 subkeyH = must_be_not_null(subkeyH, true);
8339 data = must_be_not_null(data, true);
8340
8341 Node* state_start = array_element_address(state, intcon(0), T_LONG);
8342 assert(state_start, "state is null");
8343 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
8344 assert(subkeyH_start, "subkeyH is null");
8345 Node* data_start = array_element_address(data, offset, T_BYTE);
8346 assert(data_start, "data is null");
8347
8348 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8349 OptoRuntime::ghash_processBlocks_Type(),
8350 stubAddr, stubName, TypePtr::BOTTOM,
8351 state_start, subkeyH_start, data_start, len);
8352 return true;
8353 }
8354
8355 //------------------------------inline_chacha20Block
8356 bool LibraryCallKit::inline_chacha20Block() {
8357 address stubAddr;
8358 const char *stubName;
8359 assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8360
8361 stubAddr = StubRoutines::chacha20Block();
8362 stubName = "chacha20Block";
8363
8364 Node* state = argument(0);
8365 Node* result = argument(1);
8366
8367 state = must_be_not_null(state, true);
8368 result = must_be_not_null(result, true);
8369
8370 Node* state_start = array_element_address(state, intcon(0), T_INT);
8371 assert(state_start, "state is null");
8372 Node* result_start = array_element_address(result, intcon(0), T_BYTE);
8373 assert(result_start, "result is null");
8374
8375 Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8376 OptoRuntime::chacha20Block_Type(),
8377 stubAddr, stubName, TypePtr::BOTTOM,
8378 state_start, result_start);
8379 // return key stream length (int)
8380 Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8381 set_result(retvalue);
8382 return true;
8383 }
8384
8385 //------------------------------inline_kyberNtt
8386 bool LibraryCallKit::inline_kyberNtt() {
8387 address stubAddr;
8388 const char *stubName;
8389 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8390 assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8391
8392 stubAddr = StubRoutines::kyberNtt();
8393 stubName = "kyberNtt";
8394 if (!stubAddr) return false;
8395
8396 Node* coeffs = argument(0);
8397 Node* ntt_zetas = argument(1);
8398
8399 coeffs = must_be_not_null(coeffs, true);
8400 ntt_zetas = must_be_not_null(ntt_zetas, true);
8401
8402 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8403 assert(coeffs_start, "coeffs is null");
8404 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8405 assert(ntt_zetas_start, "ntt_zetas is null");
8406 Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8407 OptoRuntime::kyberNtt_Type(),
8408 stubAddr, stubName, TypePtr::BOTTOM,
8409 coeffs_start, ntt_zetas_start);
8410 // return an int
8411 Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8412 set_result(retvalue);
8413 return true;
8414 }
8415
8416 //------------------------------inline_kyberInverseNtt
8417 bool LibraryCallKit::inline_kyberInverseNtt() {
8418 address stubAddr;
8419 const char *stubName;
8420 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8421 assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8422
8423 stubAddr = StubRoutines::kyberInverseNtt();
8424 stubName = "kyberInverseNtt";
8425 if (!stubAddr) return false;
8426
8427 Node* coeffs = argument(0);
8428 Node* zetas = argument(1);
8429
8430 coeffs = must_be_not_null(coeffs, true);
8431 zetas = must_be_not_null(zetas, true);
8432
8433 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8434 assert(coeffs_start, "coeffs is null");
8435 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8436 assert(zetas_start, "inverseNtt_zetas is null");
8437 Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8438 OptoRuntime::kyberInverseNtt_Type(),
8439 stubAddr, stubName, TypePtr::BOTTOM,
8440 coeffs_start, zetas_start);
8441
8442 // return an int
8443 Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8444 set_result(retvalue);
8445 return true;
8446 }
8447
8448 //------------------------------inline_kyberNttMult
8449 bool LibraryCallKit::inline_kyberNttMult() {
8450 address stubAddr;
8451 const char *stubName;
8452 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8453 assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8454
8455 stubAddr = StubRoutines::kyberNttMult();
8456 stubName = "kyberNttMult";
8457 if (!stubAddr) return false;
8458
8459 Node* result = argument(0);
8460 Node* ntta = argument(1);
8461 Node* nttb = argument(2);
8462 Node* zetas = argument(3);
8463
8464 result = must_be_not_null(result, true);
8465 ntta = must_be_not_null(ntta, true);
8466 nttb = must_be_not_null(nttb, true);
8467 zetas = must_be_not_null(zetas, true);
8468
8469 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8470 assert(result_start, "result is null");
8471 Node* ntta_start = array_element_address(ntta, intcon(0), T_SHORT);
8472 assert(ntta_start, "ntta is null");
8473 Node* nttb_start = array_element_address(nttb, intcon(0), T_SHORT);
8474 assert(nttb_start, "nttb is null");
8475 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8476 assert(zetas_start, "nttMult_zetas is null");
8477 Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8478 OptoRuntime::kyberNttMult_Type(),
8479 stubAddr, stubName, TypePtr::BOTTOM,
8480 result_start, ntta_start, nttb_start,
8481 zetas_start);
8482
8483 // return an int
8484 Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8485 set_result(retvalue);
8486
8487 return true;
8488 }
8489
8490 //------------------------------inline_kyberAddPoly_2
8491 bool LibraryCallKit::inline_kyberAddPoly_2() {
8492 address stubAddr;
8493 const char *stubName;
8494 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8495 assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8496
8497 stubAddr = StubRoutines::kyberAddPoly_2();
8498 stubName = "kyberAddPoly_2";
8499 if (!stubAddr) return false;
8500
8501 Node* result = argument(0);
8502 Node* a = argument(1);
8503 Node* b = argument(2);
8504
8505 result = must_be_not_null(result, true);
8506 a = must_be_not_null(a, true);
8507 b = must_be_not_null(b, true);
8508
8509 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8510 assert(result_start, "result is null");
8511 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8512 assert(a_start, "a is null");
8513 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8514 assert(b_start, "b is null");
8515 Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8516 OptoRuntime::kyberAddPoly_2_Type(),
8517 stubAddr, stubName, TypePtr::BOTTOM,
8518 result_start, a_start, b_start);
8519 // return an int
8520 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8521 set_result(retvalue);
8522 return true;
8523 }
8524
8525 //------------------------------inline_kyberAddPoly_3
8526 bool LibraryCallKit::inline_kyberAddPoly_3() {
8527 address stubAddr;
8528 const char *stubName;
8529 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8530 assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8531
8532 stubAddr = StubRoutines::kyberAddPoly_3();
8533 stubName = "kyberAddPoly_3";
8534 if (!stubAddr) return false;
8535
8536 Node* result = argument(0);
8537 Node* a = argument(1);
8538 Node* b = argument(2);
8539 Node* c = argument(3);
8540
8541 result = must_be_not_null(result, true);
8542 a = must_be_not_null(a, true);
8543 b = must_be_not_null(b, true);
8544 c = must_be_not_null(c, true);
8545
8546 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8547 assert(result_start, "result is null");
8548 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8549 assert(a_start, "a is null");
8550 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8551 assert(b_start, "b is null");
8552 Node* c_start = array_element_address(c, intcon(0), T_SHORT);
8553 assert(c_start, "c is null");
8554 Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8555 OptoRuntime::kyberAddPoly_3_Type(),
8556 stubAddr, stubName, TypePtr::BOTTOM,
8557 result_start, a_start, b_start, c_start);
8558 // return an int
8559 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8560 set_result(retvalue);
8561 return true;
8562 }
8563
8564 //------------------------------inline_kyber12To16
8565 bool LibraryCallKit::inline_kyber12To16() {
8566 address stubAddr;
8567 const char *stubName;
8568 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8569 assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8570
8571 stubAddr = StubRoutines::kyber12To16();
8572 stubName = "kyber12To16";
8573 if (!stubAddr) return false;
8574
8575 Node* condensed = argument(0);
8576 Node* condensedOffs = argument(1);
8577 Node* parsed = argument(2);
8578 Node* parsedLength = argument(3);
8579
8580 condensed = must_be_not_null(condensed, true);
8581 parsed = must_be_not_null(parsed, true);
8582
8583 Node* condensed_start = array_element_address(condensed, intcon(0), T_BYTE);
8584 assert(condensed_start, "condensed is null");
8585 Node* parsed_start = array_element_address(parsed, intcon(0), T_SHORT);
8586 assert(parsed_start, "parsed is null");
8587 Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8588 OptoRuntime::kyber12To16_Type(),
8589 stubAddr, stubName, TypePtr::BOTTOM,
8590 condensed_start, condensedOffs, parsed_start, parsedLength);
8591 // return an int
8592 Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8593 set_result(retvalue);
8594 return true;
8595
8596 }
8597
8598 //------------------------------inline_kyberBarrettReduce
8599 bool LibraryCallKit::inline_kyberBarrettReduce() {
8600 address stubAddr;
8601 const char *stubName;
8602 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8603 assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8604
8605 stubAddr = StubRoutines::kyberBarrettReduce();
8606 stubName = "kyberBarrettReduce";
8607 if (!stubAddr) return false;
8608
8609 Node* coeffs = argument(0);
8610
8611 coeffs = must_be_not_null(coeffs, true);
8612
8613 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8614 assert(coeffs_start, "coeffs is null");
8615 Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8616 OptoRuntime::kyberBarrettReduce_Type(),
8617 stubAddr, stubName, TypePtr::BOTTOM,
8618 coeffs_start);
8619 // return an int
8620 Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8621 set_result(retvalue);
8622 return true;
8623 }
8624
8625 //------------------------------inline_dilithiumAlmostNtt
8626 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8627 address stubAddr;
8628 const char *stubName;
8629 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8630 assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8631
8632 stubAddr = StubRoutines::dilithiumAlmostNtt();
8633 stubName = "dilithiumAlmostNtt";
8634 if (!stubAddr) return false;
8635
8636 Node* coeffs = argument(0);
8637 Node* ntt_zetas = argument(1);
8638
8639 coeffs = must_be_not_null(coeffs, true);
8640 ntt_zetas = must_be_not_null(ntt_zetas, true);
8641
8642 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8643 assert(coeffs_start, "coeffs is null");
8644 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_INT);
8645 assert(ntt_zetas_start, "ntt_zetas is null");
8646 Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8647 OptoRuntime::dilithiumAlmostNtt_Type(),
8648 stubAddr, stubName, TypePtr::BOTTOM,
8649 coeffs_start, ntt_zetas_start);
8650 // return an int
8651 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8652 set_result(retvalue);
8653 return true;
8654 }
8655
8656 //------------------------------inline_dilithiumAlmostInverseNtt
8657 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8658 address stubAddr;
8659 const char *stubName;
8660 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8661 assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8662
8663 stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8664 stubName = "dilithiumAlmostInverseNtt";
8665 if (!stubAddr) return false;
8666
8667 Node* coeffs = argument(0);
8668 Node* zetas = argument(1);
8669
8670 coeffs = must_be_not_null(coeffs, true);
8671 zetas = must_be_not_null(zetas, true);
8672
8673 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8674 assert(coeffs_start, "coeffs is null");
8675 Node* zetas_start = array_element_address(zetas, intcon(0), T_INT);
8676 assert(zetas_start, "inverseNtt_zetas is null");
8677 Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8678 OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8679 stubAddr, stubName, TypePtr::BOTTOM,
8680 coeffs_start, zetas_start);
8681 // return an int
8682 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8683 set_result(retvalue);
8684 return true;
8685 }
8686
8687 //------------------------------inline_dilithiumNttMult
8688 bool LibraryCallKit::inline_dilithiumNttMult() {
8689 address stubAddr;
8690 const char *stubName;
8691 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8692 assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8693
8694 stubAddr = StubRoutines::dilithiumNttMult();
8695 stubName = "dilithiumNttMult";
8696 if (!stubAddr) return false;
8697
8698 Node* result = argument(0);
8699 Node* ntta = argument(1);
8700 Node* nttb = argument(2);
8701 Node* zetas = argument(3);
8702
8703 result = must_be_not_null(result, true);
8704 ntta = must_be_not_null(ntta, true);
8705 nttb = must_be_not_null(nttb, true);
8706 zetas = must_be_not_null(zetas, true);
8707
8708 Node* result_start = array_element_address(result, intcon(0), T_INT);
8709 assert(result_start, "result is null");
8710 Node* ntta_start = array_element_address(ntta, intcon(0), T_INT);
8711 assert(ntta_start, "ntta is null");
8712 Node* nttb_start = array_element_address(nttb, intcon(0), T_INT);
8713 assert(nttb_start, "nttb is null");
8714 Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8715 OptoRuntime::dilithiumNttMult_Type(),
8716 stubAddr, stubName, TypePtr::BOTTOM,
8717 result_start, ntta_start, nttb_start);
8718
8719 // return an int
8720 Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8721 set_result(retvalue);
8722
8723 return true;
8724 }
8725
8726 //------------------------------inline_dilithiumMontMulByConstant
8727 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8728 address stubAddr;
8729 const char *stubName;
8730 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8731 assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8732
8733 stubAddr = StubRoutines::dilithiumMontMulByConstant();
8734 stubName = "dilithiumMontMulByConstant";
8735 if (!stubAddr) return false;
8736
8737 Node* coeffs = argument(0);
8738 Node* constant = argument(1);
8739
8740 coeffs = must_be_not_null(coeffs, true);
8741
8742 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8743 assert(coeffs_start, "coeffs is null");
8744 Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8745 OptoRuntime::dilithiumMontMulByConstant_Type(),
8746 stubAddr, stubName, TypePtr::BOTTOM,
8747 coeffs_start, constant);
8748
8749 // return an int
8750 Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8751 set_result(retvalue);
8752 return true;
8753 }
8754
8755
8756 //------------------------------inline_dilithiumDecomposePoly
8757 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8758 address stubAddr;
8759 const char *stubName;
8760 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8761 assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8762
8763 stubAddr = StubRoutines::dilithiumDecomposePoly();
8764 stubName = "dilithiumDecomposePoly";
8765 if (!stubAddr) return false;
8766
8767 Node* input = argument(0);
8768 Node* lowPart = argument(1);
8769 Node* highPart = argument(2);
8770 Node* twoGamma2 = argument(3);
8771 Node* multiplier = argument(4);
8772
8773 input = must_be_not_null(input, true);
8774 lowPart = must_be_not_null(lowPart, true);
8775 highPart = must_be_not_null(highPart, true);
8776
8777 Node* input_start = array_element_address(input, intcon(0), T_INT);
8778 assert(input_start, "input is null");
8779 Node* lowPart_start = array_element_address(lowPart, intcon(0), T_INT);
8780 assert(lowPart_start, "lowPart is null");
8781 Node* highPart_start = array_element_address(highPart, intcon(0), T_INT);
8782 assert(highPart_start, "highPart is null");
8783
8784 Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8785 OptoRuntime::dilithiumDecomposePoly_Type(),
8786 stubAddr, stubName, TypePtr::BOTTOM,
8787 input_start, lowPart_start, highPart_start,
8788 twoGamma2, multiplier);
8789
8790 // return an int
8791 Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8792 set_result(retvalue);
8793 return true;
8794 }
8795
8796 bool LibraryCallKit::inline_base64_encodeBlock() {
8797 address stubAddr;
8798 const char *stubName;
8799 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8800 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8801 stubAddr = StubRoutines::base64_encodeBlock();
8802 stubName = "encodeBlock";
8803
8804 if (!stubAddr) return false;
8805 Node* base64obj = argument(0);
8806 Node* src = argument(1);
8807 Node* offset = argument(2);
8808 Node* len = argument(3);
8809 Node* dest = argument(4);
8810 Node* dp = argument(5);
8811 Node* isURL = argument(6);
8812
8813 src = must_be_not_null(src, true);
8814 dest = must_be_not_null(dest, true);
8815
8816 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8817 assert(src_start, "source array is null");
8818 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8819 assert(dest_start, "destination array is null");
8820
8821 Node* base64 = make_runtime_call(RC_LEAF,
8822 OptoRuntime::base64_encodeBlock_Type(),
8823 stubAddr, stubName, TypePtr::BOTTOM,
8824 src_start, offset, len, dest_start, dp, isURL);
8825 return true;
8826 }
8827
8828 bool LibraryCallKit::inline_base64_decodeBlock() {
8829 address stubAddr;
8830 const char *stubName;
8831 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8832 assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8833 stubAddr = StubRoutines::base64_decodeBlock();
8834 stubName = "decodeBlock";
8835
8836 if (!stubAddr) return false;
8837 Node* base64obj = argument(0);
8838 Node* src = argument(1);
8839 Node* src_offset = argument(2);
8840 Node* len = argument(3);
8841 Node* dest = argument(4);
8842 Node* dest_offset = argument(5);
8843 Node* isURL = argument(6);
8844 Node* isMIME = argument(7);
8845
8846 src = must_be_not_null(src, true);
8847 dest = must_be_not_null(dest, true);
8848
8849 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8850 assert(src_start, "source array is null");
8851 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8852 assert(dest_start, "destination array is null");
8853
8854 Node* call = make_runtime_call(RC_LEAF,
8855 OptoRuntime::base64_decodeBlock_Type(),
8856 stubAddr, stubName, TypePtr::BOTTOM,
8857 src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8858 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8859 set_result(result);
8860 return true;
8861 }
8862
8863 bool LibraryCallKit::inline_poly1305_processBlocks() {
8864 address stubAddr;
8865 const char *stubName;
8866 assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8867 assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8868 stubAddr = StubRoutines::poly1305_processBlocks();
8869 stubName = "poly1305_processBlocks";
8870
8871 if (!stubAddr) return false;
8872 null_check_receiver(); // null-check receiver
8873 if (stopped()) return true;
8874
8875 Node* input = argument(1);
8876 Node* input_offset = argument(2);
8877 Node* len = argument(3);
8878 Node* alimbs = argument(4);
8879 Node* rlimbs = argument(5);
8880
8881 input = must_be_not_null(input, true);
8882 alimbs = must_be_not_null(alimbs, true);
8883 rlimbs = must_be_not_null(rlimbs, true);
8884
8885 Node* input_start = array_element_address(input, input_offset, T_BYTE);
8886 assert(input_start, "input array is null");
8887 Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8888 assert(acc_start, "acc array is null");
8889 Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8890 assert(r_start, "r array is null");
8891
8892 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8893 OptoRuntime::poly1305_processBlocks_Type(),
8894 stubAddr, stubName, TypePtr::BOTTOM,
8895 input_start, len, acc_start, r_start);
8896 return true;
8897 }
8898
8899 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8900 address stubAddr;
8901 const char *stubName;
8902 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8903 assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8904 stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8905 stubName = "intpoly_montgomeryMult_P256";
8906
8907 if (!stubAddr) return false;
8908 null_check_receiver(); // null-check receiver
8909 if (stopped()) return true;
8910
8911 Node* a = argument(1);
8912 Node* b = argument(2);
8913 Node* r = argument(3);
8914
8915 a = must_be_not_null(a, true);
8916 b = must_be_not_null(b, true);
8917 r = must_be_not_null(r, true);
8918
8919 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8920 assert(a_start, "a array is null");
8921 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8922 assert(b_start, "b array is null");
8923 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8924 assert(r_start, "r array is null");
8925
8926 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8927 OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8928 stubAddr, stubName, TypePtr::BOTTOM,
8929 a_start, b_start, r_start);
8930 return true;
8931 }
8932
8933 bool LibraryCallKit::inline_intpoly_assign() {
8934 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8935 assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8936 const char *stubName = "intpoly_assign";
8937 address stubAddr = StubRoutines::intpoly_assign();
8938 if (!stubAddr) return false;
8939
8940 Node* set = argument(0);
8941 Node* a = argument(1);
8942 Node* b = argument(2);
8943 Node* arr_length = load_array_length(a);
8944
8945 a = must_be_not_null(a, true);
8946 b = must_be_not_null(b, true);
8947
8948 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8949 assert(a_start, "a array is null");
8950 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8951 assert(b_start, "b array is null");
8952
8953 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8954 OptoRuntime::intpoly_assign_Type(),
8955 stubAddr, stubName, TypePtr::BOTTOM,
8956 set, a_start, b_start, arr_length);
8957 return true;
8958 }
8959
8960 //------------------------------inline_digestBase_implCompress-----------------------
8961 //
8962 // Calculate MD5 for single-block byte[] array.
8963 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8964 //
8965 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8966 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8967 //
8968 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8969 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8970 //
8971 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8972 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8973 //
8974 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8975 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8976 //
8977 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8978 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8979
8980 Node* digestBase_obj = argument(0);
8981 Node* src = argument(1); // type oop
8982 Node* ofs = argument(2); // type int
8983
8984 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8985 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8986 // failed array check
8987 return false;
8988 }
8989 // Figure out the size and type of the elements we will be copying.
8990 BasicType src_elem = src_type->elem()->array_element_basic_type();
8991 if (src_elem != T_BYTE) {
8992 return false;
8993 }
8994 // 'src_start' points to src array + offset
8995 src = must_be_not_null(src, true);
8996 Node* src_start = array_element_address(src, ofs, src_elem);
8997 Node* state = nullptr;
8998 Node* block_size = nullptr;
8999 address stubAddr;
9000 const char *stubName;
9001
9002 switch(id) {
9003 case vmIntrinsics::_md5_implCompress:
9004 assert(UseMD5Intrinsics, "need MD5 instruction support");
9005 state = get_state_from_digest_object(digestBase_obj, T_INT);
9006 stubAddr = StubRoutines::md5_implCompress();
9007 stubName = "md5_implCompress";
9008 break;
9009 case vmIntrinsics::_sha_implCompress:
9010 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9011 state = get_state_from_digest_object(digestBase_obj, T_INT);
9012 stubAddr = StubRoutines::sha1_implCompress();
9013 stubName = "sha1_implCompress";
9014 break;
9015 case vmIntrinsics::_sha2_implCompress:
9016 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9017 state = get_state_from_digest_object(digestBase_obj, T_INT);
9018 stubAddr = StubRoutines::sha256_implCompress();
9019 stubName = "sha256_implCompress";
9020 break;
9021 case vmIntrinsics::_sha5_implCompress:
9022 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9023 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9024 stubAddr = StubRoutines::sha512_implCompress();
9025 stubName = "sha512_implCompress";
9026 break;
9027 case vmIntrinsics::_sha3_implCompress:
9028 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9029 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9030 stubAddr = StubRoutines::sha3_implCompress();
9031 stubName = "sha3_implCompress";
9032 block_size = get_block_size_from_digest_object(digestBase_obj);
9033 if (block_size == nullptr) return false;
9034 break;
9035 default:
9036 fatal_unexpected_iid(id);
9037 return false;
9038 }
9039 if (state == nullptr) return false;
9040
9041 assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9042 if (stubAddr == nullptr) return false;
9043
9044 // Call the stub.
9045 Node* call;
9046 if (block_size == nullptr) {
9047 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9048 stubAddr, stubName, TypePtr::BOTTOM,
9049 src_start, state);
9050 } else {
9051 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9052 stubAddr, stubName, TypePtr::BOTTOM,
9053 src_start, state, block_size);
9054 }
9055
9056 return true;
9057 }
9058
9059 //------------------------------inline_double_keccak
9060 bool LibraryCallKit::inline_double_keccak() {
9061 address stubAddr;
9062 const char *stubName;
9063 assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9064 assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9065
9066 stubAddr = StubRoutines::double_keccak();
9067 stubName = "double_keccak";
9068 if (!stubAddr) return false;
9069
9070 Node* status0 = argument(0);
9071 Node* status1 = argument(1);
9072
9073 status0 = must_be_not_null(status0, true);
9074 status1 = must_be_not_null(status1, true);
9075
9076 Node* status0_start = array_element_address(status0, intcon(0), T_LONG);
9077 assert(status0_start, "status0 is null");
9078 Node* status1_start = array_element_address(status1, intcon(0), T_LONG);
9079 assert(status1_start, "status1 is null");
9080 Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9081 OptoRuntime::double_keccak_Type(),
9082 stubAddr, stubName, TypePtr::BOTTOM,
9083 status0_start, status1_start);
9084 // return an int
9085 Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9086 set_result(retvalue);
9087 return true;
9088 }
9089
9090
9091 //------------------------------inline_digestBase_implCompressMB-----------------------
9092 //
9093 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9094 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9095 //
9096 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9097 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9098 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9099 assert((uint)predicate < 5, "sanity");
9100 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9101
9102 Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9103 Node* src = argument(1); // byte[] array
9104 Node* ofs = argument(2); // type int
9105 Node* limit = argument(3); // type int
9106
9107 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9108 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9109 // failed array check
9110 return false;
9111 }
9112 // Figure out the size and type of the elements we will be copying.
9113 BasicType src_elem = src_type->elem()->array_element_basic_type();
9114 if (src_elem != T_BYTE) {
9115 return false;
9116 }
9117 // 'src_start' points to src array + offset
9118 src = must_be_not_null(src, false);
9119 Node* src_start = array_element_address(src, ofs, src_elem);
9120
9121 const char* klass_digestBase_name = nullptr;
9122 const char* stub_name = nullptr;
9123 address stub_addr = nullptr;
9124 BasicType elem_type = T_INT;
9125
9126 switch (predicate) {
9127 case 0:
9128 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9129 klass_digestBase_name = "sun/security/provider/MD5";
9130 stub_name = "md5_implCompressMB";
9131 stub_addr = StubRoutines::md5_implCompressMB();
9132 }
9133 break;
9134 case 1:
9135 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9136 klass_digestBase_name = "sun/security/provider/SHA";
9137 stub_name = "sha1_implCompressMB";
9138 stub_addr = StubRoutines::sha1_implCompressMB();
9139 }
9140 break;
9141 case 2:
9142 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9143 klass_digestBase_name = "sun/security/provider/SHA2";
9144 stub_name = "sha256_implCompressMB";
9145 stub_addr = StubRoutines::sha256_implCompressMB();
9146 }
9147 break;
9148 case 3:
9149 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9150 klass_digestBase_name = "sun/security/provider/SHA5";
9151 stub_name = "sha512_implCompressMB";
9152 stub_addr = StubRoutines::sha512_implCompressMB();
9153 elem_type = T_LONG;
9154 }
9155 break;
9156 case 4:
9157 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9158 klass_digestBase_name = "sun/security/provider/SHA3";
9159 stub_name = "sha3_implCompressMB";
9160 stub_addr = StubRoutines::sha3_implCompressMB();
9161 elem_type = T_LONG;
9162 }
9163 break;
9164 default:
9165 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9166 }
9167 if (klass_digestBase_name != nullptr) {
9168 assert(stub_addr != nullptr, "Stub is generated");
9169 if (stub_addr == nullptr) return false;
9170
9171 // get DigestBase klass to lookup for SHA klass
9172 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9173 assert(tinst != nullptr, "digestBase_obj is not instance???");
9174 assert(tinst->is_loaded(), "DigestBase is not loaded");
9175
9176 ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9177 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9178 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9179 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9180 }
9181 return false;
9182 }
9183
9184 //------------------------------inline_digestBase_implCompressMB-----------------------
9185 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9186 BasicType elem_type, address stubAddr, const char *stubName,
9187 Node* src_start, Node* ofs, Node* limit) {
9188 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9189 const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9190 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9191 digest_obj = _gvn.transform(digest_obj);
9192
9193 Node* state = get_state_from_digest_object(digest_obj, elem_type);
9194 if (state == nullptr) return false;
9195
9196 Node* block_size = nullptr;
9197 if (strcmp("sha3_implCompressMB", stubName) == 0) {
9198 block_size = get_block_size_from_digest_object(digest_obj);
9199 if (block_size == nullptr) return false;
9200 }
9201
9202 // Call the stub.
9203 Node* call;
9204 if (block_size == nullptr) {
9205 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9206 OptoRuntime::digestBase_implCompressMB_Type(false),
9207 stubAddr, stubName, TypePtr::BOTTOM,
9208 src_start, state, ofs, limit);
9209 } else {
9210 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9211 OptoRuntime::digestBase_implCompressMB_Type(true),
9212 stubAddr, stubName, TypePtr::BOTTOM,
9213 src_start, state, block_size, ofs, limit);
9214 }
9215
9216 // return ofs (int)
9217 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9218 set_result(result);
9219
9220 return true;
9221 }
9222
9223 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9224 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9225 assert(UseAES, "need AES instruction support");
9226 address stubAddr = nullptr;
9227 const char *stubName = nullptr;
9228 stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9229 stubName = "galoisCounterMode_AESCrypt";
9230
9231 if (stubAddr == nullptr) return false;
9232
9233 Node* in = argument(0);
9234 Node* inOfs = argument(1);
9235 Node* len = argument(2);
9236 Node* ct = argument(3);
9237 Node* ctOfs = argument(4);
9238 Node* out = argument(5);
9239 Node* outOfs = argument(6);
9240 Node* gctr_object = argument(7);
9241 Node* ghash_object = argument(8);
9242
9243 // (1) in, ct and out are arrays.
9244 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9245 const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9246 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9247 assert( in_type != nullptr && in_type->elem() != Type::BOTTOM &&
9248 ct_type != nullptr && ct_type->elem() != Type::BOTTOM &&
9249 out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9250
9251 // checks are the responsibility of the caller
9252 Node* in_start = in;
9253 Node* ct_start = ct;
9254 Node* out_start = out;
9255 if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9256 assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9257 in_start = array_element_address(in, inOfs, T_BYTE);
9258 ct_start = array_element_address(ct, ctOfs, T_BYTE);
9259 out_start = array_element_address(out, outOfs, T_BYTE);
9260 }
9261
9262 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9263 // (because of the predicated logic executed earlier).
9264 // so we cast it here safely.
9265 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9266 Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9267 Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9268 Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9269 Node* state = load_field_from_object(ghash_object, "state", "[J");
9270
9271 if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9272 return false;
9273 }
9274 // cast it to what we know it will be at runtime
9275 const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9276 assert(tinst != nullptr, "GCTR obj is null");
9277 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9278 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9279 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9280 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9281 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9282 const TypeOopPtr* xtype = aklass->as_instance_type();
9283 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9284 aescrypt_object = _gvn.transform(aescrypt_object);
9285 // we need to get the start of the aescrypt_object's expanded key array
9286 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9287 if (k_start == nullptr) return false;
9288 // similarly, get the start address of the r vector
9289 Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9290 Node* state_start = array_element_address(state, intcon(0), T_LONG);
9291 Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9292
9293
9294 // Call the stub, passing params
9295 Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9296 OptoRuntime::galoisCounterMode_aescrypt_Type(),
9297 stubAddr, stubName, TypePtr::BOTTOM,
9298 in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9299
9300 // return cipher length (int)
9301 Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9302 set_result(retvalue);
9303
9304 return true;
9305 }
9306
9307 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9308 // Return node representing slow path of predicate check.
9309 // the pseudo code we want to emulate with this predicate is:
9310 // for encryption:
9311 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9312 // for decryption:
9313 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9314 // note cipher==plain is more conservative than the original java code but that's OK
9315 //
9316
9317 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9318 // The receiver was checked for null already.
9319 Node* objGCTR = argument(7);
9320 // Load embeddedCipher field of GCTR object.
9321 Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9322 assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9323
9324 // get AESCrypt klass for instanceOf check
9325 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9326 // will have same classloader as CipherBlockChaining object
9327 const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9328 assert(tinst != nullptr, "GCTR obj is null");
9329 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9330
9331 // we want to do an instanceof comparison against the AESCrypt class
9332 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9333 if (!klass_AESCrypt->is_loaded()) {
9334 // if AESCrypt is not even loaded, we never take the intrinsic fast path
9335 Node* ctrl = control();
9336 set_control(top()); // no regular fast path
9337 return ctrl;
9338 }
9339
9340 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9341 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9342 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9343 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9344 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9345
9346 return instof_false; // even if it is null
9347 }
9348
9349 //------------------------------get_state_from_digest_object-----------------------
9350 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9351 const char* state_type;
9352 switch (elem_type) {
9353 case T_BYTE: state_type = "[B"; break;
9354 case T_INT: state_type = "[I"; break;
9355 case T_LONG: state_type = "[J"; break;
9356 default: ShouldNotReachHere();
9357 }
9358 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9359 assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9360 if (digest_state == nullptr) return (Node *) nullptr;
9361
9362 // now have the array, need to get the start address of the state array
9363 Node* state = array_element_address(digest_state, intcon(0), elem_type);
9364 return state;
9365 }
9366
9367 //------------------------------get_block_size_from_sha3_object----------------------------------
9368 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9369 Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9370 assert (block_size != nullptr, "sanity");
9371 return block_size;
9372 }
9373
9374 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9375 // Return node representing slow path of predicate check.
9376 // the pseudo code we want to emulate with this predicate is:
9377 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9378 //
9379 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9380 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9381 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9382 assert((uint)predicate < 5, "sanity");
9383
9384 // The receiver was checked for null already.
9385 Node* digestBaseObj = argument(0);
9386
9387 // get DigestBase klass for instanceOf check
9388 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9389 assert(tinst != nullptr, "digestBaseObj is null");
9390 assert(tinst->is_loaded(), "DigestBase is not loaded");
9391
9392 const char* klass_name = nullptr;
9393 switch (predicate) {
9394 case 0:
9395 if (UseMD5Intrinsics) {
9396 // we want to do an instanceof comparison against the MD5 class
9397 klass_name = "sun/security/provider/MD5";
9398 }
9399 break;
9400 case 1:
9401 if (UseSHA1Intrinsics) {
9402 // we want to do an instanceof comparison against the SHA class
9403 klass_name = "sun/security/provider/SHA";
9404 }
9405 break;
9406 case 2:
9407 if (UseSHA256Intrinsics) {
9408 // we want to do an instanceof comparison against the SHA2 class
9409 klass_name = "sun/security/provider/SHA2";
9410 }
9411 break;
9412 case 3:
9413 if (UseSHA512Intrinsics) {
9414 // we want to do an instanceof comparison against the SHA5 class
9415 klass_name = "sun/security/provider/SHA5";
9416 }
9417 break;
9418 case 4:
9419 if (UseSHA3Intrinsics) {
9420 // we want to do an instanceof comparison against the SHA3 class
9421 klass_name = "sun/security/provider/SHA3";
9422 }
9423 break;
9424 default:
9425 fatal("unknown SHA intrinsic predicate: %d", predicate);
9426 }
9427
9428 ciKlass* klass = nullptr;
9429 if (klass_name != nullptr) {
9430 klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9431 }
9432 if ((klass == nullptr) || !klass->is_loaded()) {
9433 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9434 Node* ctrl = control();
9435 set_control(top()); // no intrinsic path
9436 return ctrl;
9437 }
9438 ciInstanceKlass* instklass = klass->as_instance_klass();
9439
9440 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9441 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9442 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9443 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9444
9445 return instof_false; // even if it is null
9446 }
9447
9448 //-------------inline_fma-----------------------------------
9449 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9450 Node *a = nullptr;
9451 Node *b = nullptr;
9452 Node *c = nullptr;
9453 Node* result = nullptr;
9454 switch (id) {
9455 case vmIntrinsics::_fmaD:
9456 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9457 // no receiver since it is static method
9458 a = argument(0);
9459 b = argument(2);
9460 c = argument(4);
9461 result = _gvn.transform(new FmaDNode(a, b, c));
9462 break;
9463 case vmIntrinsics::_fmaF:
9464 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9465 a = argument(0);
9466 b = argument(1);
9467 c = argument(2);
9468 result = _gvn.transform(new FmaFNode(a, b, c));
9469 break;
9470 default:
9471 fatal_unexpected_iid(id); break;
9472 }
9473 set_result(result);
9474 return true;
9475 }
9476
9477 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9478 // argument(0) is receiver
9479 Node* codePoint = argument(1);
9480 Node* n = nullptr;
9481
9482 switch (id) {
9483 case vmIntrinsics::_isDigit :
9484 n = new DigitNode(control(), codePoint);
9485 break;
9486 case vmIntrinsics::_isLowerCase :
9487 n = new LowerCaseNode(control(), codePoint);
9488 break;
9489 case vmIntrinsics::_isUpperCase :
9490 n = new UpperCaseNode(control(), codePoint);
9491 break;
9492 case vmIntrinsics::_isWhitespace :
9493 n = new WhitespaceNode(control(), codePoint);
9494 break;
9495 default:
9496 fatal_unexpected_iid(id);
9497 }
9498
9499 set_result(_gvn.transform(n));
9500 return true;
9501 }
9502
9503 bool LibraryCallKit::inline_profileBoolean() {
9504 Node* counts = argument(1);
9505 const TypeAryPtr* ary = nullptr;
9506 ciArray* aobj = nullptr;
9507 if (counts->is_Con()
9508 && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9509 && (aobj = ary->const_oop()->as_array()) != nullptr
9510 && (aobj->length() == 2)) {
9511 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9512 jint false_cnt = aobj->element_value(0).as_int();
9513 jint true_cnt = aobj->element_value(1).as_int();
9514
9515 if (C->log() != nullptr) {
9516 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9517 false_cnt, true_cnt);
9518 }
9519
9520 if (false_cnt + true_cnt == 0) {
9521 // According to profile, never executed.
9522 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9523 Deoptimization::Action_reinterpret);
9524 return true;
9525 }
9526
9527 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9528 // is a number of each value occurrences.
9529 Node* result = argument(0);
9530 if (false_cnt == 0 || true_cnt == 0) {
9531 // According to profile, one value has been never seen.
9532 int expected_val = (false_cnt == 0) ? 1 : 0;
9533
9534 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9535 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9536
9537 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9538 Node* fast_path = _gvn.transform(new IfTrueNode(check));
9539 Node* slow_path = _gvn.transform(new IfFalseNode(check));
9540
9541 { // Slow path: uncommon trap for never seen value and then reexecute
9542 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9543 // the value has been seen at least once.
9544 PreserveJVMState pjvms(this);
9545 PreserveReexecuteState preexecs(this);
9546 jvms()->set_should_reexecute(true);
9547
9548 set_control(slow_path);
9549 set_i_o(i_o());
9550
9551 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9552 Deoptimization::Action_reinterpret);
9553 }
9554 // The guard for never seen value enables sharpening of the result and
9555 // returning a constant. It allows to eliminate branches on the same value
9556 // later on.
9557 set_control(fast_path);
9558 result = intcon(expected_val);
9559 }
9560 // Stop profiling.
9561 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9562 // By replacing method body with profile data (represented as ProfileBooleanNode
9563 // on IR level) we effectively disable profiling.
9564 // It enables full speed execution once optimized code is generated.
9565 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9566 C->record_for_igvn(profile);
9567 set_result(profile);
9568 return true;
9569 } else {
9570 // Continue profiling.
9571 // Profile data isn't available at the moment. So, execute method's bytecode version.
9572 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9573 // is compiled and counters aren't available since corresponding MethodHandle
9574 // isn't a compile-time constant.
9575 return false;
9576 }
9577 }
9578
9579 bool LibraryCallKit::inline_isCompileConstant() {
9580 Node* n = argument(0);
9581 set_result(n->is_Con() ? intcon(1) : intcon(0));
9582 return true;
9583 }
9584
9585 //------------------------------- inline_getObjectSize --------------------------------------
9586 //
9587 // Calculate the runtime size of the object/array.
9588 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9589 //
9590 bool LibraryCallKit::inline_getObjectSize() {
9591 Node* obj = argument(3);
9592 Node* klass_node = load_object_klass(obj);
9593
9594 jint layout_con = Klass::_lh_neutral_value;
9595 Node* layout_val = get_layout_helper(klass_node, layout_con);
9596 int layout_is_con = (layout_val == nullptr);
9597
9598 if (layout_is_con) {
9599 // Layout helper is constant, can figure out things at compile time.
9600
9601 if (Klass::layout_helper_is_instance(layout_con)) {
9602 // Instance case: layout_con contains the size itself.
9603 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9604 set_result(size);
9605 } else {
9606 // Array case: size is round(header + element_size*arraylength).
9607 // Since arraylength is different for every array instance, we have to
9608 // compute the whole thing at runtime.
9609
9610 Node* arr_length = load_array_length(obj);
9611
9612 int round_mask = MinObjAlignmentInBytes - 1;
9613 int hsize = Klass::layout_helper_header_size(layout_con);
9614 int eshift = Klass::layout_helper_log2_element_size(layout_con);
9615
9616 if ((round_mask & ~right_n_bits(eshift)) == 0) {
9617 round_mask = 0; // strength-reduce it if it goes away completely
9618 }
9619 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9620 Node* header_size = intcon(hsize + round_mask);
9621
9622 Node* lengthx = ConvI2X(arr_length);
9623 Node* headerx = ConvI2X(header_size);
9624
9625 Node* abody = lengthx;
9626 if (eshift != 0) {
9627 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9628 }
9629 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9630 if (round_mask != 0) {
9631 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9632 }
9633 size = ConvX2L(size);
9634 set_result(size);
9635 }
9636 } else {
9637 // Layout helper is not constant, need to test for array-ness at runtime.
9638
9639 enum { _instance_path = 1, _array_path, PATH_LIMIT };
9640 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9641 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9642 record_for_igvn(result_reg);
9643
9644 Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9645 if (array_ctl != nullptr) {
9646 // Array case: size is round(header + element_size*arraylength).
9647 // Since arraylength is different for every array instance, we have to
9648 // compute the whole thing at runtime.
9649
9650 PreserveJVMState pjvms(this);
9651 set_control(array_ctl);
9652 Node* arr_length = load_array_length(obj);
9653
9654 int round_mask = MinObjAlignmentInBytes - 1;
9655 Node* mask = intcon(round_mask);
9656
9657 Node* hss = intcon(Klass::_lh_header_size_shift);
9658 Node* hsm = intcon(Klass::_lh_header_size_mask);
9659 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9660 header_size = _gvn.transform(new AndINode(header_size, hsm));
9661 header_size = _gvn.transform(new AddINode(header_size, mask));
9662
9663 // There is no need to mask or shift this value.
9664 // The semantics of LShiftINode include an implicit mask to 0x1F.
9665 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9666 Node* elem_shift = layout_val;
9667
9668 Node* lengthx = ConvI2X(arr_length);
9669 Node* headerx = ConvI2X(header_size);
9670
9671 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9672 Node* size = _gvn.transform(new AddXNode(headerx, abody));
9673 if (round_mask != 0) {
9674 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9675 }
9676 size = ConvX2L(size);
9677
9678 result_reg->init_req(_array_path, control());
9679 result_val->init_req(_array_path, size);
9680 }
9681
9682 if (!stopped()) {
9683 // Instance case: the layout helper gives us instance size almost directly,
9684 // but we need to mask out the _lh_instance_slow_path_bit.
9685 Node* size = ConvI2X(layout_val);
9686 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9687 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9688 size = _gvn.transform(new AndXNode(size, mask));
9689 size = ConvX2L(size);
9690
9691 result_reg->init_req(_instance_path, control());
9692 result_val->init_req(_instance_path, size);
9693 }
9694
9695 set_result(result_reg, result_val);
9696 }
9697
9698 return true;
9699 }
9700
9701 //------------------------------- inline_blackhole --------------------------------------
9702 //
9703 // Make sure all arguments to this node are alive.
9704 // This matches methods that were requested to be blackholed through compile commands.
9705 //
9706 bool LibraryCallKit::inline_blackhole() {
9707 assert(callee()->is_static(), "Should have been checked before: only static methods here");
9708 assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9709 assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9710
9711 // Blackhole node pinches only the control, not memory. This allows
9712 // the blackhole to be pinned in the loop that computes blackholed
9713 // values, but have no other side effects, like breaking the optimizations
9714 // across the blackhole.
9715
9716 Node* bh = _gvn.transform(new BlackholeNode(control()));
9717 set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9718
9719 // Bind call arguments as blackhole arguments to keep them alive
9720 uint nargs = callee()->arg_size();
9721 for (uint i = 0; i < nargs; i++) {
9722 bh->add_req(argument(i));
9723 }
9724
9725 return true;
9726 }
9727
9728 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9729 const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9730 if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9731 return nullptr; // box klass is not Float16
9732 }
9733
9734 // Null check; get notnull casted pointer
9735 Node* null_ctl = top();
9736 Node* not_null_box = null_check_oop(box, &null_ctl, true);
9737 // If not_null_box is dead, only null-path is taken
9738 if (stopped()) {
9739 set_control(null_ctl);
9740 return nullptr;
9741 }
9742 assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9743 const TypePtr* adr_type = C->alias_type(field)->adr_type();
9744 Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9745 return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9746 }
9747
9748 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9749 PreserveReexecuteState preexecs(this);
9750 jvms()->set_should_reexecute(true);
9751
9752 const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9753 Node* klass_node = makecon(klass_type);
9754 Node* box = new_instance(klass_node);
9755
9756 Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9757 const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9758
9759 Node* field_store = _gvn.transform(access_store_at(box,
9760 value_field,
9761 value_adr_type,
9762 value,
9763 TypeInt::SHORT,
9764 T_SHORT,
9765 IN_HEAP));
9766 set_memory(field_store, value_adr_type);
9767 return box;
9768 }
9769
9770 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9771 if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9772 !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9773 return false;
9774 }
9775
9776 const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9777 if (box_type == nullptr || box_type->const_oop() == nullptr) {
9778 return false;
9779 }
9780
9781 ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9782 const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9783 ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9784 ciSymbols::short_signature(),
9785 false);
9786 assert(field != nullptr, "");
9787
9788 // Transformed nodes
9789 Node* fld1 = nullptr;
9790 Node* fld2 = nullptr;
9791 Node* fld3 = nullptr;
9792 switch(num_args) {
9793 case 3:
9794 fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9795 if (fld3 == nullptr) {
9796 return false;
9797 }
9798 fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9799 // fall-through
9800 case 2:
9801 fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9802 if (fld2 == nullptr) {
9803 return false;
9804 }
9805 fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9806 // fall-through
9807 case 1:
9808 fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9809 if (fld1 == nullptr) {
9810 return false;
9811 }
9812 fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9813 break;
9814 default: fatal("Unsupported number of arguments %d", num_args);
9815 }
9816
9817 Node* result = nullptr;
9818 switch (id) {
9819 // Unary operations
9820 case vmIntrinsics::_sqrt_float16:
9821 result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9822 break;
9823 // Ternary operations
9824 case vmIntrinsics::_fma_float16:
9825 result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9826 break;
9827 default:
9828 fatal_unexpected_iid(id);
9829 break;
9830 }
9831 result = _gvn.transform(new ReinterpretHF2SNode(result));
9832 set_result(box_fp16_value(float16_box_type, field, result));
9833 return true;
9834 }
9835