1 /*
2 * Copyright (c) 1999, 2026, 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/ciSymbols.hpp"
27 #include "ci/ciUtilities.inline.hpp"
28 #include "classfile/vmIntrinsics.hpp"
29 #include "compiler/compileBroker.hpp"
30 #include "compiler/compileLog.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "jfr/support/jfrIntrinsics.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "oops/klass.inline.hpp"
35 #include "oops/objArrayKlass.hpp"
36 #include "opto/addnode.hpp"
37 #include "opto/arraycopynode.hpp"
38 #include "opto/c2compiler.hpp"
39 #include "opto/castnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/convertnode.hpp"
42 #include "opto/countbitsnode.hpp"
43 #include "opto/idealKit.hpp"
44 #include "opto/library_call.hpp"
45 #include "opto/mathexactnode.hpp"
46 #include "opto/mulnode.hpp"
47 #include "opto/narrowptrnode.hpp"
48 #include "opto/opaquenode.hpp"
49 #include "opto/parse.hpp"
50 #include "opto/rootnode.hpp"
51 #include "opto/runtime.hpp"
52 #include "opto/subnode.hpp"
53 #include "opto/vectornode.hpp"
54 #include "prims/jvmtiExport.hpp"
55 #include "prims/jvmtiThreadState.hpp"
56 #include "prims/unsafe.hpp"
57 #include "runtime/jniHandles.inline.hpp"
58 #include "runtime/mountUnmountDisabler.hpp"
59 #include "runtime/objectMonitor.hpp"
60 #include "runtime/sharedRuntime.hpp"
61 #include "runtime/stubRoutines.hpp"
62 #include "utilities/macros.hpp"
63 #include "utilities/powerOfTwo.hpp"
64
65 //---------------------------make_vm_intrinsic----------------------------
66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
67 vmIntrinsicID id = m->intrinsic_id();
68 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
69
70 if (!m->is_loaded()) {
71 // Do not attempt to inline unloaded methods.
72 return nullptr;
73 }
74
75 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
76 bool is_available = false;
77
78 {
79 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
80 // the compiler must transition to '_thread_in_vm' state because both
81 // methods access VM-internal data.
82 VM_ENTRY_MARK;
83 methodHandle mh(THREAD, m->get_Method());
84 is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
85 if (is_available && is_virtual) {
86 is_available = vmIntrinsics::does_virtual_dispatch(id);
87 }
88 }
89
90 if (is_available) {
91 assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
92 assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
93 return new LibraryIntrinsic(m, is_virtual,
94 vmIntrinsics::predicates_needed(id),
95 vmIntrinsics::does_virtual_dispatch(id),
96 id);
97 } else {
98 return nullptr;
99 }
100 }
101
102 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
103 LibraryCallKit kit(jvms, this);
104 Compile* C = kit.C;
105 int nodes = C->unique();
106 #ifndef PRODUCT
107 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
108 char buf[1000];
109 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
110 tty->print_cr("Intrinsic %s", str);
111 }
112 #endif
113 ciMethod* callee = kit.callee();
114 const int bci = kit.bci();
115 #ifdef ASSERT
116 Node* ctrl = kit.control();
117 #endif
118 // Try to inline the intrinsic.
119 if (callee->check_intrinsic_candidate() &&
120 kit.try_to_inline(_last_predicate)) {
121 const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
122 : "(intrinsic)";
123 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
124 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
125 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
126 if (C->log()) {
127 C->log()->elem("intrinsic id='%s'%s nodes='%d'",
128 vmIntrinsics::name_at(intrinsic_id()),
129 (is_virtual() ? " virtual='1'" : ""),
130 C->unique() - nodes);
131 }
132 // Push the result from the inlined method onto the stack.
133 kit.push_result();
134 return kit.transfer_exceptions_into_jvms();
135 }
136
137 // The intrinsic bailed out
138 assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
139 assert(jvms->map() == kit.map(), "Out of sync JVM state");
140 if (jvms->has_method()) {
141 // Not a root compile.
142 const char* msg;
143 if (callee->intrinsic_candidate()) {
144 msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
145 } else {
146 msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
147 : "failed to inline (intrinsic), method not annotated";
148 }
149 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
150 C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
151 } else {
152 // Root compile
153 ResourceMark rm;
154 stringStream msg_stream;
155 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
156 vmIntrinsics::name_at(intrinsic_id()),
157 is_virtual() ? " (virtual)" : "", bci);
158 const char *msg = msg_stream.freeze();
159 log_debug(jit, inlining)("%s", msg);
160 if (C->print_intrinsics() || C->print_inlining()) {
161 tty->print("%s", msg);
162 }
163 }
164 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
165
166 return nullptr;
167 }
168
169 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
170 LibraryCallKit kit(jvms, this);
171 Compile* C = kit.C;
172 int nodes = C->unique();
173 _last_predicate = predicate;
174 #ifndef PRODUCT
175 assert(is_predicated() && predicate < predicates_count(), "sanity");
176 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
177 char buf[1000];
178 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
179 tty->print_cr("Predicate for intrinsic %s", str);
180 }
181 #endif
182 ciMethod* callee = kit.callee();
183 const int bci = kit.bci();
184
185 Node* slow_ctl = kit.try_to_predicate(predicate);
186 if (!kit.failing()) {
187 const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
188 : "(intrinsic, predicate)";
189 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
190 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
191
192 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
193 if (C->log()) {
194 C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
195 vmIntrinsics::name_at(intrinsic_id()),
196 (is_virtual() ? " virtual='1'" : ""),
197 C->unique() - nodes);
198 }
199 return slow_ctl; // Could be null if the check folds.
200 }
201
202 // The intrinsic bailed out
203 if (jvms->has_method()) {
204 // Not a root compile.
205 const char* msg = "failed to generate predicate for intrinsic";
206 CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
207 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
208 } else {
209 // Root compile
210 ResourceMark rm;
211 stringStream msg_stream;
212 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
213 vmIntrinsics::name_at(intrinsic_id()),
214 is_virtual() ? " (virtual)" : "", bci);
215 const char *msg = msg_stream.freeze();
216 log_debug(jit, inlining)("%s", msg);
217 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
218 }
219 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
220 return nullptr;
221 }
222
223 bool LibraryCallKit::try_to_inline(int predicate) {
224 // Handle symbolic names for otherwise undistinguished boolean switches:
225 const bool is_store = true;
226 const bool is_compress = true;
227 const bool is_static = true;
228 const bool is_volatile = true;
229
230 if (!jvms()->has_method()) {
231 // Root JVMState has a null method.
232 assert(map()->memory()->Opcode() == Op_Parm, "");
233 // Insert the memory aliasing node
234 set_all_memory(reset_memory());
235 }
236 assert(merged_memory(), "");
237
238 switch (intrinsic_id()) {
239 case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
240 case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);
241 case vmIntrinsics::_getClass: return inline_native_getClass();
242
243 case vmIntrinsics::_ceil:
244 case vmIntrinsics::_floor:
245 case vmIntrinsics::_rint:
246 case vmIntrinsics::_dsin:
247 case vmIntrinsics::_dcos:
248 case vmIntrinsics::_dtan:
249 case vmIntrinsics::_dsinh:
250 case vmIntrinsics::_dtanh:
251 case vmIntrinsics::_dcbrt:
252 case vmIntrinsics::_dabs:
253 case vmIntrinsics::_fabs:
254 case vmIntrinsics::_iabs:
255 case vmIntrinsics::_labs:
256 case vmIntrinsics::_datan2:
257 case vmIntrinsics::_dsqrt:
258 case vmIntrinsics::_dsqrt_strict:
259 case vmIntrinsics::_dexp:
260 case vmIntrinsics::_dlog:
261 case vmIntrinsics::_dlog10:
262 case vmIntrinsics::_dpow:
263 case vmIntrinsics::_dcopySign:
264 case vmIntrinsics::_fcopySign:
265 case vmIntrinsics::_dsignum:
266 case vmIntrinsics::_roundF:
267 case vmIntrinsics::_roundD:
268 case vmIntrinsics::_fsignum: return inline_math_native(intrinsic_id());
269
270 case vmIntrinsics::_notify:
271 case vmIntrinsics::_notifyAll:
272 return inline_notify(intrinsic_id());
273
274 case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);
275 case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);
276 case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);
277 case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);
278 case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);
279 case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);
280 case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();
281 case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();
282 case vmIntrinsics::_multiplyHigh: return inline_math_multiplyHigh();
283 case vmIntrinsics::_unsignedMultiplyHigh: return inline_math_unsignedMultiplyHigh();
284 case vmIntrinsics::_negateExactI: return inline_math_negateExactI();
285 case vmIntrinsics::_negateExactL: return inline_math_negateExactL();
286 case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);
287 case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);
288
289 case vmIntrinsics::_arraycopy: return inline_arraycopy();
290
291 case vmIntrinsics::_arraySort: return inline_array_sort();
292 case vmIntrinsics::_arrayPartition: return inline_array_partition();
293
294 case vmIntrinsics::_compareToL: return inline_string_compareTo(StrIntrinsicNode::LL);
295 case vmIntrinsics::_compareToU: return inline_string_compareTo(StrIntrinsicNode::UU);
296 case vmIntrinsics::_compareToLU: return inline_string_compareTo(StrIntrinsicNode::LU);
297 case vmIntrinsics::_compareToUL: return inline_string_compareTo(StrIntrinsicNode::UL);
298
299 case vmIntrinsics::_indexOfL: return inline_string_indexOf(StrIntrinsicNode::LL);
300 case vmIntrinsics::_indexOfU: return inline_string_indexOf(StrIntrinsicNode::UU);
301 case vmIntrinsics::_indexOfUL: return inline_string_indexOf(StrIntrinsicNode::UL);
302 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
303 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
304 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
305 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
306 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
307
308 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
309
310 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
311
312 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
313 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
314 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
315 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
316
317 case vmIntrinsics::_compressStringC:
318 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
319 case vmIntrinsics::_inflateStringC:
320 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
321
322 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
323 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
324 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
325 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
326 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
327 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
328 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
329 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
330 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
331
332 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
333 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
334 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
335 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
336 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
337 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
338 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
339 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
340 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
341
342 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
343 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
344 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
345 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
346 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
347 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
348 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
349 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
350 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
351
352 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
353 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
354 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
355 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
356 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
357 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
358 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
359 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
360 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
361
362 case vmIntrinsics::_getShortUnaligned: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, true);
363 case vmIntrinsics::_getCharUnaligned: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, true);
364 case vmIntrinsics::_getIntUnaligned: return inline_unsafe_access(!is_store, T_INT, Relaxed, true);
365 case vmIntrinsics::_getLongUnaligned: return inline_unsafe_access(!is_store, T_LONG, Relaxed, true);
366
367 case vmIntrinsics::_putShortUnaligned: return inline_unsafe_access( is_store, T_SHORT, Relaxed, true);
368 case vmIntrinsics::_putCharUnaligned: return inline_unsafe_access( is_store, T_CHAR, Relaxed, true);
369 case vmIntrinsics::_putIntUnaligned: return inline_unsafe_access( is_store, T_INT, Relaxed, true);
370 case vmIntrinsics::_putLongUnaligned: return inline_unsafe_access( is_store, T_LONG, Relaxed, true);
371
372 case vmIntrinsics::_getReferenceAcquire: return inline_unsafe_access(!is_store, T_OBJECT, Acquire, false);
373 case vmIntrinsics::_getBooleanAcquire: return inline_unsafe_access(!is_store, T_BOOLEAN, Acquire, false);
374 case vmIntrinsics::_getByteAcquire: return inline_unsafe_access(!is_store, T_BYTE, Acquire, false);
375 case vmIntrinsics::_getShortAcquire: return inline_unsafe_access(!is_store, T_SHORT, Acquire, false);
376 case vmIntrinsics::_getCharAcquire: return inline_unsafe_access(!is_store, T_CHAR, Acquire, false);
377 case vmIntrinsics::_getIntAcquire: return inline_unsafe_access(!is_store, T_INT, Acquire, false);
378 case vmIntrinsics::_getLongAcquire: return inline_unsafe_access(!is_store, T_LONG, Acquire, false);
379 case vmIntrinsics::_getFloatAcquire: return inline_unsafe_access(!is_store, T_FLOAT, Acquire, false);
380 case vmIntrinsics::_getDoubleAcquire: return inline_unsafe_access(!is_store, T_DOUBLE, Acquire, false);
381
382 case vmIntrinsics::_putReferenceRelease: return inline_unsafe_access( is_store, T_OBJECT, Release, false);
383 case vmIntrinsics::_putBooleanRelease: return inline_unsafe_access( is_store, T_BOOLEAN, Release, false);
384 case vmIntrinsics::_putByteRelease: return inline_unsafe_access( is_store, T_BYTE, Release, false);
385 case vmIntrinsics::_putShortRelease: return inline_unsafe_access( is_store, T_SHORT, Release, false);
386 case vmIntrinsics::_putCharRelease: return inline_unsafe_access( is_store, T_CHAR, Release, false);
387 case vmIntrinsics::_putIntRelease: return inline_unsafe_access( is_store, T_INT, Release, false);
388 case vmIntrinsics::_putLongRelease: return inline_unsafe_access( is_store, T_LONG, Release, false);
389 case vmIntrinsics::_putFloatRelease: return inline_unsafe_access( is_store, T_FLOAT, Release, false);
390 case vmIntrinsics::_putDoubleRelease: return inline_unsafe_access( is_store, T_DOUBLE, Release, false);
391
392 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
393 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
394 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
395 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
396 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
397 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
398 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
399 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
400 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
401
402 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
403 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
404 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
405 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
406 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
407 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
408 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
409 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
410 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
411
412 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
413 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
414 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
415 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
416 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
417
418 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
419 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
420 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
421 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
422 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
423 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
424 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
425 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
426 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
427 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
428 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
429 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
430 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
431 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
432 case vmIntrinsics::_weakCompareAndSetIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Release);
433 case vmIntrinsics::_weakCompareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Volatile);
434 case vmIntrinsics::_weakCompareAndSetLongPlain: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Relaxed);
435 case vmIntrinsics::_weakCompareAndSetLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Acquire);
436 case vmIntrinsics::_weakCompareAndSetLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Release);
437 case vmIntrinsics::_weakCompareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Volatile);
438
439 case vmIntrinsics::_compareAndExchangeReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Volatile);
440 case vmIntrinsics::_compareAndExchangeReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Acquire);
441 case vmIntrinsics::_compareAndExchangeReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Release);
442 case vmIntrinsics::_compareAndExchangeByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Volatile);
443 case vmIntrinsics::_compareAndExchangeByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Acquire);
444 case vmIntrinsics::_compareAndExchangeByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Release);
445 case vmIntrinsics::_compareAndExchangeShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Volatile);
446 case vmIntrinsics::_compareAndExchangeShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Acquire);
447 case vmIntrinsics::_compareAndExchangeShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Release);
448 case vmIntrinsics::_compareAndExchangeInt: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Volatile);
449 case vmIntrinsics::_compareAndExchangeIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Acquire);
450 case vmIntrinsics::_compareAndExchangeIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Release);
451 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
452 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
453 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
454
455 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
456 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
457 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
458 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
459
460 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
461 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
462 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
463 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
464 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
465
466 case vmIntrinsics::_loadFence:
467 case vmIntrinsics::_storeFence:
468 case vmIntrinsics::_storeStoreFence:
469 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
470
471 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
472
473 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
474 case vmIntrinsics::_currentThread: return inline_native_currentThread();
475 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
476
477 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
478 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
479
480 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
481 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
482
483 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
484 "endFirstTransition", true);
485 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
486 "startFinalTransition", true);
487 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
488 "startTransition", false);
489 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
490 "endTransition", false);
491 #if INCLUDE_JVMTI
492 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
493 #endif
494
495 #ifdef JFR_HAVE_INTRINSICS
496 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
497 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
498 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
499 case vmIntrinsics::_tryUpdateEpochField: return inline_native_try_update_epoch();
500 #endif
501 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
502 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
503 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
504 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
505 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
506 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
507 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
508 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
509 case vmIntrinsics::_getLength: return inline_native_getLength();
510 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
511 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
512 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
513 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
514 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
515 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
516 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
517
518 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
519 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
520
521 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
522
523 case vmIntrinsics::_isInstance:
524 case vmIntrinsics::_isHidden:
525 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
526
527 case vmIntrinsics::_floatToRawIntBits:
528 case vmIntrinsics::_floatToIntBits:
529 case vmIntrinsics::_intBitsToFloat:
530 case vmIntrinsics::_doubleToRawLongBits:
531 case vmIntrinsics::_doubleToLongBits:
532 case vmIntrinsics::_longBitsToDouble:
533 case vmIntrinsics::_floatToFloat16:
534 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
535 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
536 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
537 case vmIntrinsics::_floatIsFinite:
538 case vmIntrinsics::_floatIsInfinite:
539 case vmIntrinsics::_doubleIsFinite:
540 case vmIntrinsics::_doubleIsInfinite: return inline_fp_range_check(intrinsic_id());
541
542 case vmIntrinsics::_numberOfLeadingZeros_i:
543 case vmIntrinsics::_numberOfLeadingZeros_l:
544 case vmIntrinsics::_numberOfTrailingZeros_i:
545 case vmIntrinsics::_numberOfTrailingZeros_l:
546 case vmIntrinsics::_bitCount_i:
547 case vmIntrinsics::_bitCount_l:
548 case vmIntrinsics::_reverse_i:
549 case vmIntrinsics::_reverse_l:
550 case vmIntrinsics::_reverseBytes_i:
551 case vmIntrinsics::_reverseBytes_l:
552 case vmIntrinsics::_reverseBytes_s:
553 case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());
554
555 case vmIntrinsics::_compress_i:
556 case vmIntrinsics::_compress_l:
557 case vmIntrinsics::_expand_i:
558 case vmIntrinsics::_expand_l: return inline_bitshuffle_methods(intrinsic_id());
559
560 case vmIntrinsics::_compareUnsigned_i:
561 case vmIntrinsics::_compareUnsigned_l: return inline_compare_unsigned(intrinsic_id());
562
563 case vmIntrinsics::_divideUnsigned_i:
564 case vmIntrinsics::_divideUnsigned_l:
565 case vmIntrinsics::_remainderUnsigned_i:
566 case vmIntrinsics::_remainderUnsigned_l: return inline_divmod_methods(intrinsic_id());
567
568 case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();
569
570 case vmIntrinsics::_Reference_get0: return inline_reference_get0();
571 case vmIntrinsics::_Reference_refersTo0: return inline_reference_refersTo0(false);
572 case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
573 case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
574 case vmIntrinsics::_Reference_clear0: return inline_reference_clear0(false);
575 case vmIntrinsics::_PhantomReference_clear0: return inline_reference_clear0(true);
576
577 case vmIntrinsics::_Class_cast: return inline_Class_cast();
578
579 case vmIntrinsics::_aescrypt_encryptBlock:
580 case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());
581
582 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
583 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
584 return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
585
586 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
587 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
588 return inline_electronicCodeBook_AESCrypt(intrinsic_id());
589
590 case vmIntrinsics::_counterMode_AESCrypt:
591 return inline_counterMode_AESCrypt(intrinsic_id());
592
593 case vmIntrinsics::_galoisCounterMode_AESCrypt:
594 return inline_galoisCounterMode_AESCrypt();
595
596 case vmIntrinsics::_md5_implCompress:
597 case vmIntrinsics::_sha_implCompress:
598 case vmIntrinsics::_sha2_implCompress:
599 case vmIntrinsics::_sha5_implCompress:
600 case vmIntrinsics::_sha3_implCompress:
601 return inline_digestBase_implCompress(intrinsic_id());
602 case vmIntrinsics::_double_keccak:
603 case vmIntrinsics::_quad_keccak:
604 return inline_keccak(intrinsic_id());
605
606 case vmIntrinsics::_digestBase_implCompressMB:
607 return inline_digestBase_implCompressMB(predicate);
608
609 case vmIntrinsics::_multiplyToLen:
610 return inline_multiplyToLen();
611
612 case vmIntrinsics::_squareToLen:
613 return inline_squareToLen();
614
615 case vmIntrinsics::_mulAdd:
616 return inline_mulAdd();
617
618 case vmIntrinsics::_montgomeryMultiply:
619 return inline_montgomeryMultiply();
620 case vmIntrinsics::_montgomerySquare:
621 return inline_montgomerySquare();
622
623 case vmIntrinsics::_bigIntegerRightShiftWorker:
624 return inline_bigIntegerShift(true);
625 case vmIntrinsics::_bigIntegerLeftShiftWorker:
626 return inline_bigIntegerShift(false);
627
628 case vmIntrinsics::_vectorizedMismatch:
629 return inline_vectorizedMismatch();
630
631 case vmIntrinsics::_ghash_processBlocks:
632 return inline_ghash_processBlocks();
633 case vmIntrinsics::_chacha20Block:
634 return inline_chacha20Block();
635 case vmIntrinsics::_kyberNtt:
636 return inline_kyberNtt();
637 case vmIntrinsics::_kyberInverseNtt:
638 return inline_kyberInverseNtt();
639 case vmIntrinsics::_kyberNttMult:
640 return inline_kyberNttMult();
641 case vmIntrinsics::_kyberAddPoly_2:
642 return inline_kyberAddPoly_2();
643 case vmIntrinsics::_kyberAddPoly_3:
644 return inline_kyberAddPoly_3();
645 case vmIntrinsics::_kyber12To16:
646 return inline_kyber12To16();
647 case vmIntrinsics::_kyberBarrettReduce:
648 return inline_kyberBarrettReduce();
649 case vmIntrinsics::_dilithiumAlmostNtt:
650 return inline_dilithiumAlmostNtt();
651 case vmIntrinsics::_dilithiumAlmostInverseNtt:
652 return inline_dilithiumAlmostInverseNtt();
653 case vmIntrinsics::_dilithiumNttMult:
654 return inline_dilithiumNttMult();
655 case vmIntrinsics::_dilithiumMontMulByConstant:
656 return inline_dilithiumMontMulByConstant();
657 case vmIntrinsics::_dilithiumDecomposePoly:
658 return inline_dilithiumDecomposePoly();
659 case vmIntrinsics::_base64_encodeBlock:
660 return inline_base64_encodeBlock();
661 case vmIntrinsics::_base64_decodeBlock:
662 return inline_base64_decodeBlock();
663 case vmIntrinsics::_poly1305_processBlocks:
664 return inline_poly1305_processBlocks();
665 case vmIntrinsics::_intpoly_montgomeryMult_P256:
666 return inline_intpoly_montgomeryMult_P256();
667 case vmIntrinsics::_intpoly_assign:
668 return inline_intpoly_assign();
669 case vmIntrinsics::_intpoly_mult_25519:
670 return inline_intpoly_mult_25519();
671 case vmIntrinsics::_intpoly_square_25519:
672 return inline_intpoly_square_25519();
673 case vmIntrinsics::_encodeISOArray:
674 case vmIntrinsics::_encodeByteISOArray:
675 return inline_encodeISOArray(false);
676 case vmIntrinsics::_encodeAsciiArray:
677 return inline_encodeISOArray(true);
678
679 case vmIntrinsics::_updateCRC32:
680 return inline_updateCRC32();
681 case vmIntrinsics::_updateBytesCRC32:
682 return inline_updateBytesCRC32();
683 case vmIntrinsics::_updateByteBufferCRC32:
684 return inline_updateByteBufferCRC32();
685
686 case vmIntrinsics::_updateBytesCRC32C:
687 return inline_updateBytesCRC32C();
688 case vmIntrinsics::_updateDirectByteBufferCRC32C:
689 return inline_updateDirectByteBufferCRC32C();
690
691 case vmIntrinsics::_updateBytesAdler32:
692 return inline_updateBytesAdler32();
693 case vmIntrinsics::_updateByteBufferAdler32:
694 return inline_updateByteBufferAdler32();
695
696 case vmIntrinsics::_profileBoolean:
697 return inline_profileBoolean();
698 case vmIntrinsics::_isCompileConstant:
699 return inline_isCompileConstant();
700
701 case vmIntrinsics::_countPositives:
702 return inline_countPositives();
703
704 case vmIntrinsics::_fmaD:
705 case vmIntrinsics::_fmaF:
706 return inline_fma(intrinsic_id());
707
708 case vmIntrinsics::_isDigit:
709 case vmIntrinsics::_isLowerCase:
710 case vmIntrinsics::_isUpperCase:
711 case vmIntrinsics::_isWhitespace:
712 return inline_character_compare(intrinsic_id());
713
714 case vmIntrinsics::_min:
715 case vmIntrinsics::_max:
716 case vmIntrinsics::_min_strict:
717 case vmIntrinsics::_max_strict:
718 case vmIntrinsics::_minL:
719 case vmIntrinsics::_maxL:
720 case vmIntrinsics::_minF:
721 case vmIntrinsics::_maxF:
722 case vmIntrinsics::_minD:
723 case vmIntrinsics::_maxD:
724 case vmIntrinsics::_minF_strict:
725 case vmIntrinsics::_maxF_strict:
726 case vmIntrinsics::_minD_strict:
727 case vmIntrinsics::_maxD_strict:
728 return inline_min_max(intrinsic_id());
729
730 case vmIntrinsics::_VectorUnaryOp:
731 return inline_vector_nary_operation(1);
732 case vmIntrinsics::_VectorBinaryOp:
733 return inline_vector_nary_operation(2);
734 case vmIntrinsics::_VectorUnaryLibOp:
735 return inline_vector_call(1);
736 case vmIntrinsics::_VectorBinaryLibOp:
737 return inline_vector_call(2);
738 case vmIntrinsics::_VectorTernaryOp:
739 return inline_vector_nary_operation(3);
740 case vmIntrinsics::_VectorFromBitsCoerced:
741 return inline_vector_frombits_coerced();
742 case vmIntrinsics::_VectorMaskOp:
743 return inline_vector_mask_operation();
744 case vmIntrinsics::_VectorLoadOp:
745 return inline_vector_mem_operation(/*is_store=*/false);
746 case vmIntrinsics::_VectorLoadMaskedOp:
747 return inline_vector_mem_masked_operation(/*is_store*/false);
748 case vmIntrinsics::_VectorStoreOp:
749 return inline_vector_mem_operation(/*is_store=*/true);
750 case vmIntrinsics::_VectorStoreMaskedOp:
751 return inline_vector_mem_masked_operation(/*is_store=*/true);
752 case vmIntrinsics::_VectorGatherOp:
753 return inline_vector_gather_scatter(/*is_scatter*/ false);
754 case vmIntrinsics::_VectorScatterOp:
755 return inline_vector_gather_scatter(/*is_scatter*/ true);
756 case vmIntrinsics::_VectorReductionCoerced:
757 return inline_vector_reduction();
758 case vmIntrinsics::_VectorTest:
759 return inline_vector_test();
760 case vmIntrinsics::_VectorBlend:
761 return inline_vector_blend();
762 case vmIntrinsics::_VectorRearrange:
763 return inline_vector_rearrange();
764 case vmIntrinsics::_VectorSelectFrom:
765 return inline_vector_select_from();
766 case vmIntrinsics::_VectorCompare:
767 return inline_vector_compare();
768 case vmIntrinsics::_VectorBroadcastInt:
769 return inline_vector_broadcast_int();
770 case vmIntrinsics::_VectorConvert:
771 return inline_vector_convert();
772 case vmIntrinsics::_VectorInsert:
773 return inline_vector_insert();
774 case vmIntrinsics::_VectorExtract:
775 return inline_vector_extract();
776 case vmIntrinsics::_VectorCompressExpand:
777 return inline_vector_compress_expand();
778 case vmIntrinsics::_VectorSelectFromTwoVectorOp:
779 return inline_vector_select_from_two_vectors();
780 case vmIntrinsics::_IndexVector:
781 return inline_index_vector();
782 case vmIntrinsics::_IndexPartiallyInUpperRange:
783 return inline_index_partially_in_upper_range();
784
785 case vmIntrinsics::_getObjectSize:
786 return inline_getObjectSize();
787
788 case vmIntrinsics::_blackhole:
789 return inline_blackhole();
790
791 default:
792 // If you get here, it may be that someone has added a new intrinsic
793 // to the list in vmIntrinsics.hpp without implementing it here.
794 #ifndef PRODUCT
795 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
796 tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
797 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
798 }
799 #endif
800 return false;
801 }
802 }
803
804 Node* LibraryCallKit::try_to_predicate(int predicate) {
805 if (!jvms()->has_method()) {
806 // Root JVMState has a null method.
807 assert(map()->memory()->Opcode() == Op_Parm, "");
808 // Insert the memory aliasing node
809 set_all_memory(reset_memory());
810 }
811 assert(merged_memory(), "");
812
813 switch (intrinsic_id()) {
814 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
815 return inline_cipherBlockChaining_AESCrypt_predicate(false);
816 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
817 return inline_cipherBlockChaining_AESCrypt_predicate(true);
818 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
819 return inline_electronicCodeBook_AESCrypt_predicate(false);
820 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
821 return inline_electronicCodeBook_AESCrypt_predicate(true);
822 case vmIntrinsics::_counterMode_AESCrypt:
823 return inline_counterMode_AESCrypt_predicate();
824 case vmIntrinsics::_digestBase_implCompressMB:
825 return inline_digestBase_implCompressMB_predicate(predicate);
826 case vmIntrinsics::_galoisCounterMode_AESCrypt:
827 return inline_galoisCounterMode_AESCrypt_predicate();
828
829 default:
830 // If you get here, it may be that someone has added a new intrinsic
831 // to the list in vmIntrinsics.hpp without implementing it here.
832 #ifndef PRODUCT
833 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
834 tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
835 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
836 }
837 #endif
838 Node* slow_ctl = control();
839 set_control(top()); // No fast path intrinsic
840 return slow_ctl;
841 }
842 }
843
844 //------------------------------set_result-------------------------------
845 // Helper function for finishing intrinsics.
846 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
847 record_for_igvn(region);
848 set_control(_gvn.transform(region));
849 set_result( _gvn.transform(value));
850 assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
851 }
852
853 RegionNode* LibraryCallKit::create_bailout() {
854 RegionNode* bailout = new RegionNode(1);
855 record_for_igvn(bailout);
856 return bailout;
857 }
858
859 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
860 if (bailout->req() > 1) {
861 bailout = _gvn.transform(bailout)->as_Region();
862 Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
863 Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
864 C->root()->add_req(halt);
865 }
866 return stopped();
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, bool with_opaque) {
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 if (with_opaque) {
925 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
926 }
927 Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
928 if (is_neg != nullptr && pos_index != nullptr) {
929 // Emulate effect of Parse::adjust_map_after_if.
930 Node* ccast = new CastIINode(control(), index, TypeInt::POS);
931 (*pos_index) = _gvn.transform(ccast);
932 }
933 return is_neg;
934 }
935
936 // Make sure that 'position' is a valid limit index, in [0..length].
937 // There are two equivalent plans for checking this:
938 // A. (offset + copyLength) unsigned<= arrayLength
939 // B. offset <= (arrayLength - copyLength)
940 // We require that all of the values above, except for the sum and
941 // difference, are already known to be non-negative.
942 // Plan A is robust in the face of overflow, if offset and copyLength
943 // are both hugely positive.
944 //
945 // Plan B is less direct and intuitive, but it does not overflow at
946 // all, since the difference of two non-negatives is always
947 // representable. Whenever Java methods must perform the equivalent
948 // check they generally use Plan B instead of Plan A.
949 // For the moment we use Plan A.
950 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
951 Node* subseq_length,
952 Node* array_length,
953 RegionNode* region,
954 bool with_opaque) {
955 if (stopped())
956 return nullptr; // already stopped
957 bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
958 if (zero_offset && subseq_length->eqv_uncast(array_length))
959 return nullptr; // common case of whole-array copy
960 Node* last = subseq_length;
961 if (!zero_offset) // last += offset
962 last = _gvn.transform(new AddINode(last, offset));
963 Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
964 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
965 if (with_opaque) {
966 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
967 }
968 Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
969 return is_over;
970 }
971
972 // Emit range checks for the given String.value byte array
973 void LibraryCallKit::generate_string_range_check(Node* array,
974 Node* offset,
975 Node* count,
976 bool char_count,
977 RegionNode* region) {
978 if (stopped()) {
979 return; // already stopped
980 }
981 if (char_count) {
982 // Convert char count to byte count
983 count = _gvn.transform(new LShiftINode(count, intcon(1)));
984 }
985 // Offset and count must not be negative
986 generate_negative_guard(offset, region, nullptr, true);
987 generate_negative_guard(count, region, nullptr, true);
988 // Offset + count must not exceed length of array
989 generate_limit_guard(offset, count, load_array_length(array), region, true);
990 }
991
992 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
993 bool is_immutable) {
994 ciKlass* thread_klass = env()->Thread_klass();
995 const Type* thread_type
996 = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
997
998 Node* thread = _gvn.transform(new ThreadLocalNode());
999 Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1000 tls_output = thread;
1001
1002 Node* thread_obj_handle
1003 = (is_immutable
1004 ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1005 TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1006 : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1007 thread_obj_handle = _gvn.transform(thread_obj_handle);
1008
1009 DecoratorSet decorators = IN_NATIVE;
1010 if (is_immutable) {
1011 decorators |= C2_IMMUTABLE_MEMORY;
1012 }
1013 return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1014 }
1015
1016 //--------------------------generate_current_thread--------------------
1017 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1018 return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1019 /*is_immutable*/false);
1020 }
1021
1022 //--------------------------generate_virtual_thread--------------------
1023 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1024 return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1025 !C->method()->changes_current_thread());
1026 }
1027
1028 //------------------------------make_string_method_node------------------------
1029 // Helper method for String intrinsic functions. This version is called with
1030 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1031 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1032 // containing the lengths of str1 and str2.
1033 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1034 Node* result = nullptr;
1035 switch (opcode) {
1036 case Op_StrIndexOf:
1037 result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1038 str1_start, cnt1, str2_start, cnt2, ae);
1039 break;
1040 case Op_StrComp:
1041 result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1042 str1_start, cnt1, str2_start, cnt2, ae);
1043 break;
1044 case Op_StrEquals:
1045 // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1046 // Use the constant length if there is one because optimized match rule may exist.
1047 result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1048 str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1049 break;
1050 default:
1051 ShouldNotReachHere();
1052 return nullptr;
1053 }
1054
1055 // All these intrinsics have checks.
1056 C->set_has_split_ifs(true); // Has chance for split-if optimization
1057 clear_upper_avx();
1058
1059 return _gvn.transform(result);
1060 }
1061
1062 //------------------------------inline_string_compareTo------------------------
1063 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1064 Node* arg1 = argument(0);
1065 Node* arg2 = argument(1);
1066
1067 arg1 = must_be_not_null(arg1, true);
1068 arg2 = must_be_not_null(arg2, true);
1069
1070 // Get start addr and length of first argument
1071 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1072 Node* arg1_cnt = load_array_length(arg1);
1073
1074 // Get start addr and length of second argument
1075 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1076 Node* arg2_cnt = load_array_length(arg2);
1077
1078 Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1079 set_result(result);
1080 return true;
1081 }
1082
1083 //------------------------------inline_string_equals------------------------
1084 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1085 Node* arg1 = argument(0);
1086 Node* arg2 = argument(1);
1087
1088 // paths (plus control) merge
1089 RegionNode* region = new RegionNode(3);
1090 Node* phi = new PhiNode(region, TypeInt::BOOL);
1091
1092 if (!stopped()) {
1093
1094 arg1 = must_be_not_null(arg1, true);
1095 arg2 = must_be_not_null(arg2, true);
1096
1097 // Get start addr and length of first argument
1098 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1099 Node* arg1_cnt = load_array_length(arg1);
1100
1101 // Get start addr and length of second argument
1102 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1103 Node* arg2_cnt = load_array_length(arg2);
1104
1105 // Check for arg1_cnt != arg2_cnt
1106 Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1107 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1108 Node* if_ne = generate_slow_guard(bol, nullptr);
1109 if (if_ne != nullptr) {
1110 phi->init_req(2, intcon(0));
1111 region->init_req(2, if_ne);
1112 }
1113
1114 // Check for count == 0 is done by assembler code for StrEquals.
1115
1116 if (!stopped()) {
1117 Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1118 phi->init_req(1, equals);
1119 region->init_req(1, control());
1120 }
1121 }
1122
1123 // post merge
1124 set_control(_gvn.transform(region));
1125 record_for_igvn(region);
1126
1127 set_result(_gvn.transform(phi));
1128 return true;
1129 }
1130
1131 //------------------------------inline_array_equals----------------------------
1132 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1133 assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1134 Node* arg1 = argument(0);
1135 Node* arg2 = argument(1);
1136
1137 const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1138 set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae)));
1139 clear_upper_avx();
1140
1141 return true;
1142 }
1143
1144
1145 //------------------------------inline_countPositives------------------------------
1146 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1147 bool LibraryCallKit::inline_countPositives() {
1148 assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1149 // no receiver since it is static method
1150 Node* ba = argument(0);
1151 Node* offset = argument(1);
1152 Node* len = argument(2);
1153
1154 ba = must_be_not_null(ba, true);
1155 RegionNode* bailout = create_bailout();
1156 generate_string_range_check(ba, offset, len, false, bailout);
1157 if (check_bailout(bailout)) {
1158 return true;
1159 }
1160
1161 Node* ba_start = array_element_address(ba, offset, T_BYTE);
1162 Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1163 set_result(_gvn.transform(result));
1164 clear_upper_avx();
1165 return true;
1166 }
1167
1168 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1169 Node* index = argument(0);
1170 Node* length = bt == T_INT ? argument(1) : argument(2);
1171 if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1172 return false;
1173 }
1174
1175 // check that length is positive
1176 Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1177 Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1178
1179 {
1180 BuildCutout unless(this, len_pos_bol, PROB_MAX);
1181 uncommon_trap(Deoptimization::Reason_intrinsic,
1182 Deoptimization::Action_make_not_entrant);
1183 }
1184
1185 if (stopped()) {
1186 // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1187 return true;
1188 }
1189
1190 // length is now known positive, add a cast node to make this explicit
1191 jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1192 Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1193 control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1194 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1195 casted_length = _gvn.transform(casted_length);
1196 replace_in_map(length, casted_length);
1197 length = casted_length;
1198
1199 // Use an unsigned comparison for the range check itself
1200 Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1201 BoolTest::mask btest = BoolTest::lt;
1202 Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1203 RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1204 _gvn.set_type(rc, rc->Value(&_gvn));
1205 if (!rc_bool->is_Con()) {
1206 record_for_igvn(rc);
1207 }
1208 set_control(_gvn.transform(new IfTrueNode(rc)));
1209 {
1210 PreserveJVMState pjvms(this);
1211 set_control(_gvn.transform(new IfFalseNode(rc)));
1212 uncommon_trap(Deoptimization::Reason_range_check,
1213 Deoptimization::Action_make_not_entrant);
1214 }
1215
1216 if (stopped()) {
1217 // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1218 return true;
1219 }
1220
1221 // index is now known to be >= 0 and < length, cast it
1222 Node* result = ConstraintCastNode::make_cast_for_basic_type(
1223 control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1224 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1225 result = _gvn.transform(result);
1226 set_result(result);
1227 replace_in_map(index, result);
1228 return true;
1229 }
1230
1231 //------------------------------inline_string_indexOf------------------------
1232 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1233 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1234 return false;
1235 }
1236 Node* src = argument(0);
1237 Node* tgt = argument(1);
1238
1239 // Make the merge point
1240 RegionNode* result_rgn = new RegionNode(4);
1241 Node* result_phi = new PhiNode(result_rgn, TypeInt::INT);
1242
1243 src = must_be_not_null(src, true);
1244 tgt = must_be_not_null(tgt, true);
1245
1246 // Get start addr and length of source string
1247 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1248 Node* src_count = load_array_length(src);
1249
1250 // Get start addr and length of substring
1251 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1252 Node* tgt_count = load_array_length(tgt);
1253
1254 Node* result = nullptr;
1255 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1256
1257 if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1258 // Divide src size by 2 if String is UTF16 encoded
1259 src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1260 }
1261 if (ae == StrIntrinsicNode::UU) {
1262 // Divide substring size by 2 if String is UTF16 encoded
1263 tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1264 }
1265
1266 if (call_opt_stub) {
1267 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1268 StubRoutines::_string_indexof_array[ae],
1269 "stringIndexOf", TypePtr::BOTTOM, src_start,
1270 src_count, tgt_start, tgt_count);
1271 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1272 } else {
1273 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1274 result_rgn, result_phi, ae);
1275 }
1276 if (result != nullptr) {
1277 result_phi->init_req(3, result);
1278 result_rgn->init_req(3, control());
1279 }
1280 set_control(_gvn.transform(result_rgn));
1281 record_for_igvn(result_rgn);
1282 set_result(_gvn.transform(result_phi));
1283
1284 return true;
1285 }
1286
1287 //-----------------------------inline_string_indexOfI-----------------------
1288 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1289 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1290 return false;
1291 }
1292
1293 assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1294 Node* src = argument(0); // byte[]
1295 Node* src_count = argument(1); // char count
1296 Node* tgt = argument(2); // byte[]
1297 Node* tgt_count = argument(3); // char count
1298 Node* from_index = argument(4); // char index
1299
1300 src = must_be_not_null(src, true);
1301 tgt = must_be_not_null(tgt, true);
1302
1303 // Multiply byte array index by 2 if String is UTF16 encoded
1304 Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1305 src_count = _gvn.transform(new SubINode(src_count, from_index));
1306 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1307 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1308
1309 // Range checks
1310 RegionNode* bailout = create_bailout();
1311 generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1312 generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1313 if (check_bailout(bailout)) {
1314 return true;
1315 }
1316
1317 RegionNode* region = new RegionNode(5);
1318 Node* phi = new PhiNode(region, TypeInt::INT);
1319 Node* result = nullptr;
1320
1321 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1322
1323 if (call_opt_stub) {
1324 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1325 StubRoutines::_string_indexof_array[ae],
1326 "stringIndexOf", TypePtr::BOTTOM, src_start,
1327 src_count, tgt_start, tgt_count);
1328 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1329 } else {
1330 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1331 region, phi, ae);
1332 }
1333 if (result != nullptr) {
1334 // The result is index relative to from_index if substring was found, -1 otherwise.
1335 // Generate code which will fold into cmove.
1336 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1337 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1338
1339 Node* if_lt = generate_slow_guard(bol, nullptr);
1340 if (if_lt != nullptr) {
1341 // result == -1
1342 phi->init_req(3, result);
1343 region->init_req(3, if_lt);
1344 }
1345 if (!stopped()) {
1346 result = _gvn.transform(new AddINode(result, from_index));
1347 phi->init_req(4, result);
1348 region->init_req(4, control());
1349 }
1350 }
1351
1352 set_control(_gvn.transform(region));
1353 record_for_igvn(region);
1354 set_result(_gvn.transform(phi));
1355 clear_upper_avx();
1356
1357 return true;
1358 }
1359
1360 // Create StrIndexOfNode with fast path checks
1361 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1362 RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1363 // Check for substr count > string count
1364 Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1365 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1366 Node* if_gt = generate_slow_guard(bol, nullptr);
1367 if (if_gt != nullptr) {
1368 phi->init_req(1, intcon(-1));
1369 region->init_req(1, if_gt);
1370 }
1371 if (!stopped()) {
1372 // Check for substr count == 0
1373 cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1374 bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1375 Node* if_zero = generate_slow_guard(bol, nullptr);
1376 if (if_zero != nullptr) {
1377 phi->init_req(2, intcon(0));
1378 region->init_req(2, if_zero);
1379 }
1380 }
1381 if (!stopped()) {
1382 return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1383 }
1384 return nullptr;
1385 }
1386
1387 //-----------------------------inline_string_indexOfChar-----------------------
1388 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1389 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1390 return false;
1391 }
1392 if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1393 return false;
1394 }
1395 assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1396 Node* src = argument(0); // byte[]
1397 Node* int_ch = argument(1);
1398 Node* from_index = argument(2);
1399 Node* max = argument(3);
1400
1401 src = must_be_not_null(src, true);
1402
1403 Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1404 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1405 Node* src_count = _gvn.transform(new SubINode(max, from_index));
1406
1407 // Range checks
1408 RegionNode* bailout = create_bailout();
1409 generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1410 if (check_bailout(bailout)) {
1411 return true;
1412 }
1413
1414 // Check for int_ch >= 0
1415 Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1416 Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1417 {
1418 BuildCutout unless(this, int_ch_bol, PROB_MAX);
1419 uncommon_trap(Deoptimization::Reason_intrinsic,
1420 Deoptimization::Action_maybe_recompile);
1421 }
1422 if (stopped()) {
1423 return true;
1424 }
1425
1426 RegionNode* region = new RegionNode(3);
1427 Node* phi = new PhiNode(region, TypeInt::INT);
1428
1429 Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1430 C->set_has_split_ifs(true); // Has chance for split-if optimization
1431 _gvn.transform(result);
1432
1433 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1434 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1435
1436 Node* if_lt = generate_slow_guard(bol, nullptr);
1437 if (if_lt != nullptr) {
1438 // result == -1
1439 phi->init_req(2, result);
1440 region->init_req(2, if_lt);
1441 }
1442 if (!stopped()) {
1443 result = _gvn.transform(new AddINode(result, from_index));
1444 phi->init_req(1, result);
1445 region->init_req(1, control());
1446 }
1447 set_control(_gvn.transform(region));
1448 record_for_igvn(region);
1449 set_result(_gvn.transform(phi));
1450 clear_upper_avx();
1451
1452 return true;
1453 }
1454 //---------------------------inline_string_copy---------------------
1455 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1456 // int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1457 // int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1458 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1459 // void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1460 // void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1461 bool LibraryCallKit::inline_string_copy(bool compress) {
1462 int nargs = 5; // 2 oops, 3 ints
1463 assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1464
1465 Node* src = argument(0);
1466 Node* src_offset = argument(1);
1467 Node* dst = argument(2);
1468 Node* dst_offset = argument(3);
1469 Node* length = argument(4);
1470
1471 // Check for allocation before we add nodes that would confuse
1472 // tightly_coupled_allocation()
1473 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1474
1475 // Figure out the size and type of the elements we will be copying.
1476 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1477 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1478 if (src_type == nullptr || dst_type == nullptr) {
1479 return false;
1480 }
1481 BasicType src_elem = src_type->elem()->array_element_basic_type();
1482 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1483 assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1484 (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1485 "Unsupported array types for inline_string_copy");
1486
1487 src = must_be_not_null(src, true);
1488 dst = must_be_not_null(dst, true);
1489
1490 // Convert char[] offsets to byte[] offsets
1491 bool convert_src = (compress && src_elem == T_BYTE);
1492 bool convert_dst = (!compress && dst_elem == T_BYTE);
1493 if (convert_src) {
1494 src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1495 } else if (convert_dst) {
1496 dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1497 }
1498
1499 // Range checks
1500 RegionNode* bailout = create_bailout();
1501 generate_string_range_check(src, src_offset, length, convert_src, bailout);
1502 generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1503 if (check_bailout(bailout)) {
1504 return true;
1505 }
1506
1507 Node* src_start = array_element_address(src, src_offset, src_elem);
1508 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1509 // 'src_start' points to src array + scaled offset
1510 // 'dst_start' points to dst array + scaled offset
1511 Node* count = nullptr;
1512 if (compress) {
1513 count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1514 } else {
1515 inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1516 }
1517
1518 if (alloc != nullptr) {
1519 if (alloc->maybe_set_complete(&_gvn)) {
1520 // "You break it, you buy it."
1521 InitializeNode* init = alloc->initialization();
1522 assert(init->is_complete(), "we just did this");
1523 init->set_complete_with_arraycopy();
1524 assert(dst->is_CheckCastPP(), "sanity");
1525 assert(dst->in(0)->in(0) == init, "dest pinned");
1526 }
1527 // Do not let stores that initialize this object be reordered with
1528 // a subsequent store that would make this object accessible by
1529 // other threads.
1530 // Record what AllocateNode this StoreStore protects so that
1531 // escape analysis can go from the MemBarStoreStoreNode to the
1532 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1533 // based on the escape status of the AllocateNode.
1534 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1535 }
1536 if (compress) {
1537 set_result(_gvn.transform(count));
1538 }
1539 clear_upper_avx();
1540
1541 return true;
1542 }
1543
1544 #ifdef _LP64
1545 #define XTOP ,top() /*additional argument*/
1546 #else //_LP64
1547 #define XTOP /*no additional argument*/
1548 #endif //_LP64
1549
1550 //------------------------inline_string_toBytesU--------------------------
1551 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1552 bool LibraryCallKit::inline_string_toBytesU() {
1553 // Get the arguments.
1554 assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1555 Node* value = argument(0);
1556 Node* offset = argument(1);
1557 Node* length = argument(2);
1558
1559 Node* newcopy = nullptr;
1560
1561 // Set the original stack and the reexecute bit for the interpreter to reexecute
1562 // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1563 { PreserveReexecuteState preexecs(this);
1564 jvms()->set_should_reexecute(true);
1565
1566 value = must_be_not_null(value, true);
1567 RegionNode* bailout = create_bailout();
1568 generate_negative_guard(offset, bailout, nullptr, true);
1569 generate_negative_guard(length, bailout, nullptr, true);
1570 generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1571 // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1572 generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1573 if (check_bailout(bailout)) {
1574 return true;
1575 }
1576
1577 Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1578 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1579 newcopy = new_array(klass_node, size, 0); // no arguments to push
1580 AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1581 guarantee(alloc != nullptr, "created above");
1582
1583 // Calculate starting addresses.
1584 Node* src_start = array_element_address(value, offset, T_CHAR);
1585 Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1586
1587 // Check if dst array address is aligned to HeapWordSize
1588 bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1589 // If true, then check if src array address is aligned to HeapWordSize
1590 if (aligned) {
1591 const TypeInt* toffset = gvn().type(offset)->is_int();
1592 aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1593 toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1594 }
1595
1596 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1597 const char* copyfunc_name = "arraycopy";
1598 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1599 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1600 OptoRuntime::fast_arraycopy_Type(),
1601 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1602 src_start, dst_start, ConvI2X(length) XTOP);
1603 // Do not let reads from the cloned object float above the arraycopy.
1604 if (alloc->maybe_set_complete(&_gvn)) {
1605 // "You break it, you buy it."
1606 InitializeNode* init = alloc->initialization();
1607 assert(init->is_complete(), "we just did this");
1608 init->set_complete_with_arraycopy();
1609 assert(newcopy->is_CheckCastPP(), "sanity");
1610 assert(newcopy->in(0)->in(0) == init, "dest pinned");
1611 }
1612 // Do not let stores that initialize this object be reordered with
1613 // a subsequent store that would make this object accessible by
1614 // other threads.
1615 // Record what AllocateNode this StoreStore protects so that
1616 // escape analysis can go from the MemBarStoreStoreNode to the
1617 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1618 // based on the escape status of the AllocateNode.
1619 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1620 } // original reexecute is set back here
1621
1622 C->set_has_split_ifs(true); // Has chance for split-if optimization
1623 if (!stopped()) {
1624 set_result(newcopy);
1625 }
1626 clear_upper_avx();
1627
1628 return true;
1629 }
1630
1631 //------------------------inline_string_getCharsU--------------------------
1632 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1633 bool LibraryCallKit::inline_string_getCharsU() {
1634 assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1635 // Get the arguments.
1636 Node* src = argument(0);
1637 Node* src_begin = argument(1);
1638 Node* src_end = argument(2); // exclusive offset (i < src_end)
1639 Node* dst = argument(3);
1640 Node* dst_begin = argument(4);
1641
1642 // Check for allocation before we add nodes that would confuse
1643 // tightly_coupled_allocation()
1644 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1645
1646 // Check if a null path was taken unconditionally.
1647 src = must_be_not_null(src, true);
1648 dst = must_be_not_null(dst, true);
1649 if (stopped()) {
1650 return true;
1651 }
1652
1653 // Get length and convert char[] offset to byte[] offset
1654 Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1655 src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1656
1657 // Range checks
1658 RegionNode* bailout = create_bailout();
1659 generate_string_range_check(src, src_begin, length, true, bailout);
1660 generate_string_range_check(dst, dst_begin, length, false, bailout);
1661 if (check_bailout(bailout)) {
1662 return true;
1663 }
1664
1665 // Calculate starting addresses.
1666 Node* src_start = array_element_address(src, src_begin, T_BYTE);
1667 Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1668
1669 // Check if array addresses are aligned to HeapWordSize
1670 const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1671 const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1672 bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1673 tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1674
1675 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1676 const char* copyfunc_name = "arraycopy";
1677 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1678 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1679 OptoRuntime::fast_arraycopy_Type(),
1680 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1681 src_start, dst_start, ConvI2X(length) XTOP);
1682 // Do not let reads from the cloned object float above the arraycopy.
1683 if (alloc != nullptr) {
1684 if (alloc->maybe_set_complete(&_gvn)) {
1685 // "You break it, you buy it."
1686 InitializeNode* init = alloc->initialization();
1687 assert(init->is_complete(), "we just did this");
1688 init->set_complete_with_arraycopy();
1689 assert(dst->is_CheckCastPP(), "sanity");
1690 assert(dst->in(0)->in(0) == init, "dest pinned");
1691 }
1692 // Do not let stores that initialize this object be reordered with
1693 // a subsequent store that would make this object accessible by
1694 // other threads.
1695 // Record what AllocateNode this StoreStore protects so that
1696 // escape analysis can go from the MemBarStoreStoreNode to the
1697 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1698 // based on the escape status of the AllocateNode.
1699 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1700 } else {
1701 insert_mem_bar(Op_MemBarCPUOrder);
1702 }
1703
1704 C->set_has_split_ifs(true); // Has chance for split-if optimization
1705 return true;
1706 }
1707
1708 //----------------------inline_string_char_access----------------------------
1709 // Store/Load char to/from byte[] array.
1710 // static void StringUTF16.putChar(byte[] val, int index, int c)
1711 // static char StringUTF16.getChar(byte[] val, int index)
1712 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1713 Node* ch;
1714 if (is_store) {
1715 assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1716 ch = argument(2);
1717 } else {
1718 assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1719 ch = nullptr;
1720 }
1721 Node* value = argument(0);
1722 Node* index = argument(1);
1723
1724 // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1725 // correctly requires matched array shapes.
1726 assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1727 "sanity: byte[] and char[] bases agree");
1728 assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1729 "sanity: byte[] and char[] scales agree");
1730
1731 // Bail when getChar over constants is requested: constant folding would
1732 // reject folding mismatched char access over byte[]. A normal inlining for getChar
1733 // Java method would constant fold nicely instead.
1734 if (!is_store && value->is_Con() && index->is_Con()) {
1735 return false;
1736 }
1737
1738 // Save state and restore on bailout
1739 SavedState old_state(this);
1740
1741 value = must_be_not_null(value, true);
1742
1743 Node* adr = array_element_address(value, index, T_CHAR);
1744 if (adr->is_top()) {
1745 return false;
1746 }
1747 old_state.discard();
1748 if (is_store) {
1749 access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1750 } else {
1751 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);
1752 set_result(ch);
1753 }
1754 return true;
1755 }
1756
1757
1758 //------------------------------inline_math-----------------------------------
1759 // public static double Math.abs(double)
1760 // public static double Math.sqrt(double)
1761 // public static double Math.log(double)
1762 // public static double Math.log10(double)
1763 // public static double Math.round(double)
1764 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1765 Node* arg = argument(0);
1766 Node* n = nullptr;
1767 switch (id) {
1768 case vmIntrinsics::_dabs: n = new AbsDNode( arg); break;
1769 case vmIntrinsics::_dsqrt:
1770 case vmIntrinsics::_dsqrt_strict:
1771 n = new SqrtDNode(C, control(), arg); break;
1772 case vmIntrinsics::_ceil: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1773 case vmIntrinsics::_floor: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1774 case vmIntrinsics::_rint: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1775 case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1776 case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1777 case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1778 default: fatal_unexpected_iid(id); break;
1779 }
1780 set_result(_gvn.transform(n));
1781 return true;
1782 }
1783
1784 //------------------------------inline_math-----------------------------------
1785 // public static float Math.abs(float)
1786 // public static int Math.abs(int)
1787 // public static long Math.abs(long)
1788 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1789 Node* arg = argument(0);
1790 Node* n = nullptr;
1791 switch (id) {
1792 case vmIntrinsics::_fabs: n = new AbsFNode( arg); break;
1793 case vmIntrinsics::_iabs: n = new AbsINode( arg); break;
1794 case vmIntrinsics::_labs: n = new AbsLNode( arg); break;
1795 case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1796 case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1797 case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1798 default: fatal_unexpected_iid(id); break;
1799 }
1800 set_result(_gvn.transform(n));
1801 return true;
1802 }
1803
1804 //------------------------------runtime_math-----------------------------
1805 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1806 assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1807 "must be (DD)D or (D)D type");
1808
1809 // Inputs
1810 Node* a = argument(0);
1811 Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1812
1813 const TypePtr* no_memory_effects = nullptr;
1814 Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1815 no_memory_effects,
1816 a, top(), b, b ? top() : nullptr);
1817 Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1818 #ifdef ASSERT
1819 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1820 assert(value_top == top(), "second value must be top");
1821 #endif
1822
1823 set_result(value);
1824 return true;
1825 }
1826
1827 //------------------------------inline_math_pow-----------------------------
1828 bool LibraryCallKit::inline_math_pow() {
1829 Node* base = argument(0);
1830 Node* exp = argument(2);
1831
1832 CallNode* pow = new PowDNode(C, base, exp);
1833 set_predefined_input_for_runtime_call(pow);
1834 pow = _gvn.transform(pow)->as_CallLeafPure();
1835 set_predefined_output_for_runtime_call(pow);
1836 Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1837 record_for_igvn(pow);
1838 set_result(result);
1839 return true;
1840 }
1841
1842 //------------------------------inline_math_native-----------------------------
1843 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1844 switch (id) {
1845 case vmIntrinsics::_dsin:
1846 return StubRoutines::dsin() != nullptr ?
1847 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1848 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1849 case vmIntrinsics::_dcos:
1850 return StubRoutines::dcos() != nullptr ?
1851 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1852 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1853 case vmIntrinsics::_dtan:
1854 return StubRoutines::dtan() != nullptr ?
1855 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1856 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1857 case vmIntrinsics::_dsinh:
1858 return StubRoutines::dsinh() != nullptr ?
1859 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1860 case vmIntrinsics::_dtanh:
1861 return StubRoutines::dtanh() != nullptr ?
1862 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1863 case vmIntrinsics::_dcbrt:
1864 return StubRoutines::dcbrt() != nullptr ?
1865 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1866 case vmIntrinsics::_dexp:
1867 return StubRoutines::dexp() != nullptr ?
1868 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(), "dexp") :
1869 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1870 case vmIntrinsics::_dlog:
1871 return StubRoutines::dlog() != nullptr ?
1872 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1873 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1874 case vmIntrinsics::_dlog10:
1875 return StubRoutines::dlog10() != nullptr ?
1876 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1877 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1878
1879 case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1880 case vmIntrinsics::_ceil:
1881 case vmIntrinsics::_floor:
1882 case vmIntrinsics::_rint: return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1883
1884 case vmIntrinsics::_dsqrt:
1885 case vmIntrinsics::_dsqrt_strict:
1886 return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1887 case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_double_math(id) : false;
1888 case vmIntrinsics::_fabs: return Matcher::match_rule_supported(Op_AbsF) ? inline_math(id) : false;
1889 case vmIntrinsics::_iabs: return Matcher::match_rule_supported(Op_AbsI) ? inline_math(id) : false;
1890 case vmIntrinsics::_labs: return Matcher::match_rule_supported(Op_AbsL) ? inline_math(id) : false;
1891
1892 case vmIntrinsics::_dpow: return inline_math_pow();
1893 case vmIntrinsics::_dcopySign: return inline_double_math(id);
1894 case vmIntrinsics::_fcopySign: return inline_math(id);
1895 case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1896 case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1897 case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1898
1899 // These intrinsics are not yet correctly implemented
1900 case vmIntrinsics::_datan2:
1901 return false;
1902
1903 default:
1904 fatal_unexpected_iid(id);
1905 return false;
1906 }
1907 }
1908
1909 //----------------------------inline_notify-----------------------------------*
1910 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1911 const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1912 address func;
1913 if (id == vmIntrinsics::_notify) {
1914 func = OptoRuntime::monitor_notify_Java();
1915 } else {
1916 func = OptoRuntime::monitor_notifyAll_Java();
1917 }
1918 Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1919 make_slow_call_ex(call, env()->Throwable_klass(), false);
1920 return true;
1921 }
1922
1923
1924 //----------------------------inline_min_max-----------------------------------
1925 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1926 Node* a = nullptr;
1927 Node* b = nullptr;
1928 Node* n = nullptr;
1929 switch (id) {
1930 case vmIntrinsics::_min:
1931 case vmIntrinsics::_max:
1932 case vmIntrinsics::_minF:
1933 case vmIntrinsics::_maxF:
1934 case vmIntrinsics::_minF_strict:
1935 case vmIntrinsics::_maxF_strict:
1936 case vmIntrinsics::_min_strict:
1937 case vmIntrinsics::_max_strict:
1938 assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1939 a = argument(0);
1940 b = argument(1);
1941 break;
1942 case vmIntrinsics::_minD:
1943 case vmIntrinsics::_maxD:
1944 case vmIntrinsics::_minD_strict:
1945 case vmIntrinsics::_maxD_strict:
1946 assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1947 a = argument(0);
1948 b = argument(2);
1949 break;
1950 case vmIntrinsics::_minL:
1951 case vmIntrinsics::_maxL:
1952 assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1953 a = argument(0);
1954 b = argument(2);
1955 break;
1956 default:
1957 fatal_unexpected_iid(id);
1958 break;
1959 }
1960
1961 switch (id) {
1962 case vmIntrinsics::_min:
1963 case vmIntrinsics::_min_strict:
1964 n = new MinINode(a, b);
1965 break;
1966 case vmIntrinsics::_max:
1967 case vmIntrinsics::_max_strict:
1968 n = new MaxINode(a, b);
1969 break;
1970 case vmIntrinsics::_minF:
1971 case vmIntrinsics::_minF_strict:
1972 n = new MinFNode(a, b);
1973 break;
1974 case vmIntrinsics::_maxF:
1975 case vmIntrinsics::_maxF_strict:
1976 n = new MaxFNode(a, b);
1977 break;
1978 case vmIntrinsics::_minD:
1979 case vmIntrinsics::_minD_strict:
1980 n = new MinDNode(a, b);
1981 break;
1982 case vmIntrinsics::_maxD:
1983 case vmIntrinsics::_maxD_strict:
1984 n = new MaxDNode(a, b);
1985 break;
1986 case vmIntrinsics::_minL:
1987 n = new MinLNode(_gvn.C, a, b);
1988 break;
1989 case vmIntrinsics::_maxL:
1990 n = new MaxLNode(_gvn.C, a, b);
1991 break;
1992 default:
1993 fatal_unexpected_iid(id);
1994 break;
1995 }
1996
1997 set_result(_gvn.transform(n));
1998 return true;
1999 }
2000
2001 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2002 if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2003 env()->ArithmeticException_instance())) {
2004 // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2005 // so let's bail out intrinsic rather than risking deopting again.
2006 return false;
2007 }
2008
2009 Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2010 IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2011 Node* fast_path = _gvn.transform( new IfFalseNode(check));
2012 Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2013
2014 {
2015 PreserveJVMState pjvms(this);
2016 PreserveReexecuteState preexecs(this);
2017 jvms()->set_should_reexecute(true);
2018
2019 set_control(slow_path);
2020 set_i_o(i_o());
2021
2022 builtin_throw(Deoptimization::Reason_intrinsic,
2023 env()->ArithmeticException_instance(),
2024 /*allow_too_many_traps*/ false);
2025 }
2026
2027 set_control(fast_path);
2028 set_result(math);
2029 return true;
2030 }
2031
2032 template <typename OverflowOp>
2033 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2034 typedef typename OverflowOp::MathOp MathOp;
2035
2036 MathOp* mathOp = new MathOp(arg1, arg2);
2037 Node* operation = _gvn.transform( mathOp );
2038 Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2039 return inline_math_mathExact(operation, ofcheck);
2040 }
2041
2042 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2043 return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2044 }
2045
2046 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2047 return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2048 }
2049
2050 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2051 return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2052 }
2053
2054 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2055 return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2056 }
2057
2058 bool LibraryCallKit::inline_math_negateExactI() {
2059 return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2060 }
2061
2062 bool LibraryCallKit::inline_math_negateExactL() {
2063 return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2064 }
2065
2066 bool LibraryCallKit::inline_math_multiplyExactI() {
2067 return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2068 }
2069
2070 bool LibraryCallKit::inline_math_multiplyExactL() {
2071 return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2072 }
2073
2074 bool LibraryCallKit::inline_math_multiplyHigh() {
2075 set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2076 return true;
2077 }
2078
2079 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2080 set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2081 return true;
2082 }
2083
2084 inline int
2085 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2086 const TypePtr* base_type = TypePtr::NULL_PTR;
2087 if (base != nullptr) base_type = _gvn.type(base)->isa_ptr();
2088 if (base_type == nullptr) {
2089 // Unknown type.
2090 return Type::AnyPtr;
2091 } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2092 // Since this is a null+long form, we have to switch to a rawptr.
2093 base = _gvn.transform(new CastX2PNode(offset));
2094 offset = MakeConX(0);
2095 return Type::RawPtr;
2096 } else if (base_type->base() == Type::RawPtr) {
2097 return Type::RawPtr;
2098 } else if (base_type->isa_oopptr()) {
2099 // Base is never null => always a heap address.
2100 if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2101 return Type::OopPtr;
2102 }
2103 // Offset is small => always a heap address.
2104 const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2105 if (offset_type != nullptr &&
2106 base_type->offset() == 0 && // (should always be?)
2107 offset_type->_lo >= 0 &&
2108 !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2109 return Type::OopPtr;
2110 } else if (type == T_OBJECT) {
2111 // off heap access to an oop doesn't make any sense. Has to be on
2112 // heap.
2113 return Type::OopPtr;
2114 }
2115 // Otherwise, it might either be oop+off or null+addr.
2116 return Type::AnyPtr;
2117 } else {
2118 // No information:
2119 return Type::AnyPtr;
2120 }
2121 }
2122
2123 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2124 Node* uncasted_base = base;
2125 int kind = classify_unsafe_addr(uncasted_base, offset, type);
2126 if (kind == Type::RawPtr) {
2127 return off_heap_plus_addr(uncasted_base, offset);
2128 } else if (kind == Type::AnyPtr) {
2129 assert(base == uncasted_base, "unexpected base change");
2130 if (can_cast) {
2131 if (!_gvn.type(base)->speculative_maybe_null() &&
2132 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2133 // According to profiling, this access is always on
2134 // heap. Casting the base to not null and thus avoiding membars
2135 // around the access should allow better optimizations
2136 Node* null_ctl = top();
2137 base = null_check_oop(base, &null_ctl, true, true, true);
2138 assert(null_ctl->is_top(), "no null control here");
2139 return basic_plus_adr(base, offset);
2140 } else if (_gvn.type(base)->speculative_always_null() &&
2141 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2142 // According to profiling, this access is always off
2143 // heap.
2144 base = null_assert(base);
2145 Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2146 offset = MakeConX(0);
2147 return off_heap_plus_addr(raw_base, offset);
2148 }
2149 }
2150 // We don't know if it's an on heap or off heap access. Fall back
2151 // to raw memory access.
2152 Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2153 return off_heap_plus_addr(raw, offset);
2154 } else {
2155 assert(base == uncasted_base, "unexpected base change");
2156 // We know it's an on heap access so base can't be null
2157 if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2158 base = must_be_not_null(base, true);
2159 }
2160 return basic_plus_adr(base, offset);
2161 }
2162 }
2163
2164 //--------------------------inline_number_methods-----------------------------
2165 // inline int Integer.numberOfLeadingZeros(int)
2166 // inline int Long.numberOfLeadingZeros(long)
2167 //
2168 // inline int Integer.numberOfTrailingZeros(int)
2169 // inline int Long.numberOfTrailingZeros(long)
2170 //
2171 // inline int Integer.bitCount(int)
2172 // inline int Long.bitCount(long)
2173 //
2174 // inline char Character.reverseBytes(char)
2175 // inline short Short.reverseBytes(short)
2176 // inline int Integer.reverseBytes(int)
2177 // inline long Long.reverseBytes(long)
2178 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2179 Node* arg = argument(0);
2180 Node* n = nullptr;
2181 switch (id) {
2182 case vmIntrinsics::_numberOfLeadingZeros_i: n = new CountLeadingZerosINode( arg); break;
2183 case vmIntrinsics::_numberOfLeadingZeros_l: n = new CountLeadingZerosLNode( arg); break;
2184 case vmIntrinsics::_numberOfTrailingZeros_i: n = new CountTrailingZerosINode(arg); break;
2185 case vmIntrinsics::_numberOfTrailingZeros_l: n = new CountTrailingZerosLNode(arg); break;
2186 case vmIntrinsics::_bitCount_i: n = new PopCountINode( arg); break;
2187 case vmIntrinsics::_bitCount_l: n = new PopCountLNode( arg); break;
2188 case vmIntrinsics::_reverseBytes_c: n = new ReverseBytesUSNode( arg); break;
2189 case vmIntrinsics::_reverseBytes_s: n = new ReverseBytesSNode( arg); break;
2190 case vmIntrinsics::_reverseBytes_i: n = new ReverseBytesINode( arg); break;
2191 case vmIntrinsics::_reverseBytes_l: n = new ReverseBytesLNode( arg); break;
2192 case vmIntrinsics::_reverse_i: n = new ReverseINode( arg); break;
2193 case vmIntrinsics::_reverse_l: n = new ReverseLNode( arg); break;
2194 default: fatal_unexpected_iid(id); break;
2195 }
2196 set_result(_gvn.transform(n));
2197 return true;
2198 }
2199
2200 //--------------------------inline_bitshuffle_methods-----------------------------
2201 // inline int Integer.compress(int, int)
2202 // inline int Integer.expand(int, int)
2203 // inline long Long.compress(long, long)
2204 // inline long Long.expand(long, long)
2205 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2206 Node* n = nullptr;
2207 switch (id) {
2208 case vmIntrinsics::_compress_i: n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2209 case vmIntrinsics::_expand_i: n = new ExpandBitsNode(argument(0), argument(1), TypeInt::INT); break;
2210 case vmIntrinsics::_compress_l: n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2211 case vmIntrinsics::_expand_l: n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2212 default: fatal_unexpected_iid(id); break;
2213 }
2214 set_result(_gvn.transform(n));
2215 return true;
2216 }
2217
2218 //--------------------------inline_number_methods-----------------------------
2219 // inline int Integer.compareUnsigned(int, int)
2220 // inline int Long.compareUnsigned(long, long)
2221 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2222 Node* arg1 = argument(0);
2223 Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2224 Node* n = nullptr;
2225 switch (id) {
2226 case vmIntrinsics::_compareUnsigned_i: n = new CmpU3Node(arg1, arg2); break;
2227 case vmIntrinsics::_compareUnsigned_l: n = new CmpUL3Node(arg1, arg2); break;
2228 default: fatal_unexpected_iid(id); break;
2229 }
2230 set_result(_gvn.transform(n));
2231 return true;
2232 }
2233
2234 //--------------------------inline_unsigned_divmod_methods-----------------------------
2235 // inline int Integer.divideUnsigned(int, int)
2236 // inline int Integer.remainderUnsigned(int, int)
2237 // inline long Long.divideUnsigned(long, long)
2238 // inline long Long.remainderUnsigned(long, long)
2239 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2240 Node* n = nullptr;
2241 switch (id) {
2242 case vmIntrinsics::_divideUnsigned_i: {
2243 zero_check_int(argument(1));
2244 // Compile-time detect of null-exception
2245 if (stopped()) {
2246 return true; // keep the graph constructed so far
2247 }
2248 n = new UDivINode(control(), argument(0), argument(1));
2249 break;
2250 }
2251 case vmIntrinsics::_divideUnsigned_l: {
2252 zero_check_long(argument(2));
2253 // Compile-time detect of null-exception
2254 if (stopped()) {
2255 return true; // keep the graph constructed so far
2256 }
2257 n = new UDivLNode(control(), argument(0), argument(2));
2258 break;
2259 }
2260 case vmIntrinsics::_remainderUnsigned_i: {
2261 zero_check_int(argument(1));
2262 // Compile-time detect of null-exception
2263 if (stopped()) {
2264 return true; // keep the graph constructed so far
2265 }
2266 n = new UModINode(control(), argument(0), argument(1));
2267 break;
2268 }
2269 case vmIntrinsics::_remainderUnsigned_l: {
2270 zero_check_long(argument(2));
2271 // Compile-time detect of null-exception
2272 if (stopped()) {
2273 return true; // keep the graph constructed so far
2274 }
2275 n = new UModLNode(control(), argument(0), argument(2));
2276 break;
2277 }
2278 default: fatal_unexpected_iid(id); break;
2279 }
2280 set_result(_gvn.transform(n));
2281 return true;
2282 }
2283
2284 //----------------------------inline_unsafe_access----------------------------
2285
2286 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2287 // Attempt to infer a sharper value type from the offset and base type.
2288 ciKlass* sharpened_klass = nullptr;
2289
2290 // See if it is an instance field, with an object type.
2291 if (alias_type->field() != nullptr) {
2292 if (alias_type->field()->type()->is_klass()) {
2293 sharpened_klass = alias_type->field()->type()->as_klass();
2294 }
2295 }
2296
2297 const TypeOopPtr* result = nullptr;
2298 // See if it is a narrow oop array.
2299 if (adr_type->isa_aryptr()) {
2300 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2301 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2302 if (elem_type != nullptr && elem_type->is_loaded()) {
2303 // Sharpen the value type.
2304 result = elem_type;
2305 }
2306 }
2307 }
2308
2309 // The sharpened class might be unloaded if there is no class loader
2310 // contraint in place.
2311 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2312 // Sharpen the value type.
2313 result = TypeOopPtr::make_from_klass(sharpened_klass);
2314 }
2315 if (result != nullptr) {
2316 #ifndef PRODUCT
2317 if (C->print_intrinsics() || C->print_inlining()) {
2318 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2319 tty->print(" sharpened value: "); result->dump(); tty->cr();
2320 }
2321 #endif
2322 }
2323 return result;
2324 }
2325
2326 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2327 switch (kind) {
2328 case Relaxed:
2329 return MO_UNORDERED;
2330 case Opaque:
2331 return MO_RELAXED;
2332 case Acquire:
2333 return MO_ACQUIRE;
2334 case Release:
2335 return MO_RELEASE;
2336 case Volatile:
2337 return MO_SEQ_CST;
2338 default:
2339 ShouldNotReachHere();
2340 return 0;
2341 }
2342 }
2343
2344 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2345 if (callee()->is_static()) return false; // caller must have the capability!
2346 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2347 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2348 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2349 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2350
2351 if (is_reference_type(type)) {
2352 decorators |= ON_UNKNOWN_OOP_REF;
2353 }
2354
2355 if (unaligned) {
2356 decorators |= C2_UNALIGNED;
2357 }
2358
2359 #ifndef PRODUCT
2360 {
2361 ResourceMark rm;
2362 // Check the signatures.
2363 ciSignature* sig = callee()->signature();
2364 #ifdef ASSERT
2365 if (!is_store) {
2366 // Object getReference(Object base, int/long offset), etc.
2367 BasicType rtype = sig->return_type()->basic_type();
2368 assert(rtype == type, "getter must return the expected value");
2369 assert(sig->count() == 2, "oop getter has 2 arguments");
2370 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2371 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2372 } else {
2373 // void putReference(Object base, int/long offset, Object x), etc.
2374 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2375 assert(sig->count() == 3, "oop putter has 3 arguments");
2376 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2377 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2378 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2379 assert(vtype == type, "putter must accept the expected value");
2380 }
2381 #endif // ASSERT
2382 }
2383 #endif //PRODUCT
2384
2385 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2386
2387 Node* receiver = argument(0); // type: oop
2388
2389 // Build address expression.
2390 Node* heap_base_oop = top();
2391
2392 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2393 Node* base = argument(1); // type: oop
2394 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2395 Node* offset = argument(2); // type: long
2396 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2397 // to be plain byte offsets, which are also the same as those accepted
2398 // by oopDesc::field_addr.
2399 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2400 "fieldOffset must be byte-scaled");
2401 // 32-bit machines ignore the high half!
2402 offset = ConvL2X(offset);
2403
2404 // Save state and restore on bailout
2405 SavedState old_state(this);
2406
2407 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2408 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2409
2410 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2411 if (type != T_OBJECT) {
2412 decorators |= IN_NATIVE; // off-heap primitive access
2413 } else {
2414 return false; // off-heap oop accesses are not supported
2415 }
2416 } else {
2417 heap_base_oop = base; // on-heap or mixed access
2418 }
2419
2420 // Can base be null? Otherwise, always on-heap access.
2421 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2422
2423 if (!can_access_non_heap) {
2424 decorators |= IN_HEAP;
2425 }
2426
2427 Node* val = is_store ? argument(4) : nullptr;
2428
2429 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2430 if (adr_type == TypePtr::NULL_PTR) {
2431 return false; // off-heap access with zero address
2432 }
2433
2434 // Try to categorize the address.
2435 Compile::AliasType* alias_type = C->alias_type(adr_type);
2436 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2437
2438 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2439 alias_type->adr_type() == TypeAryPtr::RANGE) {
2440 return false; // not supported
2441 }
2442
2443 bool mismatched = false;
2444 BasicType bt = alias_type->basic_type();
2445 if (bt != T_ILLEGAL) {
2446 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2447 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2448 // Alias type doesn't differentiate between byte[] and boolean[]).
2449 // Use address type to get the element type.
2450 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2451 }
2452 if (is_reference_type(bt, true)) {
2453 // accessing an array field with getReference is not a mismatch
2454 bt = T_OBJECT;
2455 }
2456 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2457 // Don't intrinsify mismatched object accesses
2458 return false;
2459 }
2460 mismatched = (bt != type);
2461 } else if (alias_type->adr_type()->isa_oopptr()) {
2462 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2463 }
2464
2465 old_state.discard();
2466 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2467
2468 if (mismatched) {
2469 decorators |= C2_MISMATCHED;
2470 }
2471
2472 // First guess at the value type.
2473 const Type *value_type = Type::get_const_basic_type(type);
2474
2475 // Figure out the memory ordering.
2476 decorators |= mo_decorator_for_access_kind(kind);
2477
2478 if (!is_store && type == T_OBJECT) {
2479 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2480 if (tjp != nullptr) {
2481 value_type = tjp;
2482 }
2483 }
2484
2485 receiver = null_check(receiver);
2486 if (stopped()) {
2487 return true;
2488 }
2489 // Heap pointers get a null-check from the interpreter,
2490 // as a courtesy. However, this is not guaranteed by Unsafe,
2491 // and it is not possible to fully distinguish unintended nulls
2492 // from intended ones in this API.
2493
2494 if (!is_store) {
2495 Node* p = nullptr;
2496 // Try to constant fold a load from a constant field
2497 ciField* field = alias_type->field();
2498 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2499 // final or stable field
2500 p = make_constant_from_field(field, heap_base_oop);
2501 }
2502
2503 if (p == nullptr) { // Could not constant fold the load
2504 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2505 // Normalize the value returned by getBoolean in the following cases
2506 if (type == T_BOOLEAN &&
2507 (mismatched ||
2508 heap_base_oop == top() || // - heap_base_oop is null or
2509 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2510 // and the unsafe access is made to large offset
2511 // (i.e., larger than the maximum offset necessary for any
2512 // field access)
2513 ) {
2514 IdealKit ideal = IdealKit(this);
2515 #define __ ideal.
2516 IdealVariable normalized_result(ideal);
2517 __ declarations_done();
2518 __ set(normalized_result, p);
2519 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2520 __ set(normalized_result, ideal.ConI(1));
2521 ideal.end_if();
2522 final_sync(ideal);
2523 p = __ value(normalized_result);
2524 #undef __
2525 }
2526 }
2527 if (type == T_ADDRESS) {
2528 p = gvn().transform(new CastP2XNode(nullptr, p));
2529 p = ConvX2UL(p);
2530 }
2531 // The load node has the control of the preceding MemBarCPUOrder. All
2532 // following nodes will have the control of the MemBarCPUOrder inserted at
2533 // the end of this method. So, pushing the load onto the stack at a later
2534 // point is fine.
2535 set_result(p);
2536 } else {
2537 if (bt == T_ADDRESS) {
2538 // Repackage the long as a pointer.
2539 val = ConvL2X(val);
2540 val = gvn().transform(new CastX2PNode(val));
2541 }
2542 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2543 }
2544
2545 return true;
2546 }
2547
2548 //----------------------------inline_unsafe_load_store----------------------------
2549 // This method serves a couple of different customers (depending on LoadStoreKind):
2550 //
2551 // LS_cmp_swap:
2552 //
2553 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2554 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2555 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2556 //
2557 // LS_cmp_swap_weak:
2558 //
2559 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2560 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2561 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2562 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2563 //
2564 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2565 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2566 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2567 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2568 //
2569 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
2570 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
2571 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
2572 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
2573 //
2574 // LS_cmp_exchange:
2575 //
2576 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2577 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2578 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2579 //
2580 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
2581 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
2582 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
2583 //
2584 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
2585 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
2586 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
2587 //
2588 // LS_get_add:
2589 //
2590 // int getAndAddInt( Object o, long offset, int delta)
2591 // long getAndAddLong(Object o, long offset, long delta)
2592 //
2593 // LS_get_set:
2594 //
2595 // int getAndSet(Object o, long offset, int newValue)
2596 // long getAndSet(Object o, long offset, long newValue)
2597 // Object getAndSet(Object o, long offset, Object newValue)
2598 //
2599 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2600 // This basic scheme here is the same as inline_unsafe_access, but
2601 // differs in enough details that combining them would make the code
2602 // overly confusing. (This is a true fact! I originally combined
2603 // them, but even I was confused by it!) As much code/comments as
2604 // possible are retained from inline_unsafe_access though to make
2605 // the correspondences clearer. - dl
2606
2607 if (callee()->is_static()) return false; // caller must have the capability!
2608
2609 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2610 decorators |= mo_decorator_for_access_kind(access_kind);
2611
2612 #ifndef PRODUCT
2613 BasicType rtype;
2614 {
2615 ResourceMark rm;
2616 // Check the signatures.
2617 ciSignature* sig = callee()->signature();
2618 rtype = sig->return_type()->basic_type();
2619 switch(kind) {
2620 case LS_get_add:
2621 case LS_get_set: {
2622 // Check the signatures.
2623 #ifdef ASSERT
2624 assert(rtype == type, "get and set must return the expected type");
2625 assert(sig->count() == 3, "get and set has 3 arguments");
2626 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2627 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2628 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2629 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2630 #endif // ASSERT
2631 break;
2632 }
2633 case LS_cmp_swap:
2634 case LS_cmp_swap_weak: {
2635 // Check the signatures.
2636 #ifdef ASSERT
2637 assert(rtype == T_BOOLEAN, "CAS must return boolean");
2638 assert(sig->count() == 4, "CAS has 4 arguments");
2639 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2640 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2641 #endif // ASSERT
2642 break;
2643 }
2644 case LS_cmp_exchange: {
2645 // Check the signatures.
2646 #ifdef ASSERT
2647 assert(rtype == type, "CAS must return the expected type");
2648 assert(sig->count() == 4, "CAS has 4 arguments");
2649 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2650 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2651 #endif // ASSERT
2652 break;
2653 }
2654 default:
2655 ShouldNotReachHere();
2656 }
2657 }
2658 #endif //PRODUCT
2659
2660 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2661
2662 // Get arguments:
2663 Node* receiver = nullptr;
2664 Node* base = nullptr;
2665 Node* offset = nullptr;
2666 Node* oldval = nullptr;
2667 Node* newval = nullptr;
2668 switch(kind) {
2669 case LS_cmp_swap:
2670 case LS_cmp_swap_weak:
2671 case LS_cmp_exchange: {
2672 const bool two_slot_type = type2size[type] == 2;
2673 receiver = argument(0); // type: oop
2674 base = argument(1); // type: oop
2675 offset = argument(2); // type: long
2676 oldval = argument(4); // type: oop, int, or long
2677 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
2678 break;
2679 }
2680 case LS_get_add:
2681 case LS_get_set: {
2682 receiver = argument(0); // type: oop
2683 base = argument(1); // type: oop
2684 offset = argument(2); // type: long
2685 oldval = nullptr;
2686 newval = argument(4); // type: oop, int, or long
2687 break;
2688 }
2689 default:
2690 ShouldNotReachHere();
2691 }
2692
2693 // Build field offset expression.
2694 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2695 // to be plain byte offsets, which are also the same as those accepted
2696 // by oopDesc::field_addr.
2697 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2698 // 32-bit machines ignore the high half of long offsets
2699 offset = ConvL2X(offset);
2700 // Save state and restore on bailout
2701 SavedState old_state(this);
2702 Node* adr = make_unsafe_address(base, offset,type, false);
2703 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2704
2705 Compile::AliasType* alias_type = C->alias_type(adr_type);
2706 BasicType bt = alias_type->basic_type();
2707 if (bt != T_ILLEGAL &&
2708 (is_reference_type(bt) != (type == T_OBJECT))) {
2709 // Don't intrinsify mismatched object accesses.
2710 return false;
2711 }
2712
2713 old_state.discard();
2714
2715 // For CAS, unlike inline_unsafe_access, there seems no point in
2716 // trying to refine types. Just use the coarse types here.
2717 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2718 const Type *value_type = Type::get_const_basic_type(type);
2719
2720 switch (kind) {
2721 case LS_get_set:
2722 case LS_cmp_exchange: {
2723 if (type == T_OBJECT) {
2724 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2725 if (tjp != nullptr) {
2726 value_type = tjp;
2727 }
2728 }
2729 break;
2730 }
2731 case LS_cmp_swap:
2732 case LS_cmp_swap_weak:
2733 case LS_get_add:
2734 break;
2735 default:
2736 ShouldNotReachHere();
2737 }
2738
2739 // Null check receiver.
2740 receiver = null_check(receiver);
2741 if (stopped()) {
2742 return true;
2743 }
2744
2745 int alias_idx = C->get_alias_index(adr_type);
2746
2747 if (is_reference_type(type)) {
2748 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2749
2750 // Transformation of a value which could be null pointer (CastPP #null)
2751 // could be delayed during Parse (for example, in adjust_map_after_if()).
2752 // Execute transformation here to avoid barrier generation in such case.
2753 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2754 newval = _gvn.makecon(TypePtr::NULL_PTR);
2755
2756 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2757 // Refine the value to a null constant, when it is known to be null
2758 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2759 }
2760 }
2761
2762 Node* result = nullptr;
2763 switch (kind) {
2764 case LS_cmp_exchange: {
2765 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2766 oldval, newval, value_type, type, decorators);
2767 break;
2768 }
2769 case LS_cmp_swap_weak:
2770 decorators |= C2_WEAK_CMPXCHG;
2771 case LS_cmp_swap: {
2772 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
2773 oldval, newval, value_type, type, decorators);
2774 break;
2775 }
2776 case LS_get_set: {
2777 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
2778 newval, value_type, type, decorators);
2779 break;
2780 }
2781 case LS_get_add: {
2782 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
2783 newval, value_type, type, decorators);
2784 break;
2785 }
2786 default:
2787 ShouldNotReachHere();
2788 }
2789
2790 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2791 set_result(result);
2792 return true;
2793 }
2794
2795 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2796 // Regardless of form, don't allow previous ld/st to move down,
2797 // then issue acquire, release, or volatile mem_bar.
2798 insert_mem_bar(Op_MemBarCPUOrder);
2799 switch(id) {
2800 case vmIntrinsics::_loadFence:
2801 insert_mem_bar(Op_LoadFence);
2802 return true;
2803 case vmIntrinsics::_storeFence:
2804 insert_mem_bar(Op_StoreFence);
2805 return true;
2806 case vmIntrinsics::_storeStoreFence:
2807 insert_mem_bar(Op_StoreStoreFence);
2808 return true;
2809 case vmIntrinsics::_fullFence:
2810 insert_mem_bar(Op_MemBarFull);
2811 return true;
2812 default:
2813 fatal_unexpected_iid(id);
2814 return false;
2815 }
2816 }
2817
2818 bool LibraryCallKit::inline_onspinwait() {
2819 insert_mem_bar(Op_OnSpinWait);
2820 return true;
2821 }
2822
2823 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2824 if (!kls->is_Con()) {
2825 return true;
2826 }
2827 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2828 if (klsptr == nullptr) {
2829 return true;
2830 }
2831 ciInstanceKlass* ik = klsptr->instance_klass();
2832 // don't need a guard for a klass that is already initialized
2833 return !ik->is_initialized();
2834 }
2835
2836 //----------------------------inline_unsafe_writeback0-------------------------
2837 // public native void Unsafe.writeback0(long address)
2838 bool LibraryCallKit::inline_unsafe_writeback0() {
2839 if (!Matcher::has_match_rule(Op_CacheWB)) {
2840 return false;
2841 }
2842 #ifndef PRODUCT
2843 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
2844 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
2845 ciSignature* sig = callee()->signature();
2846 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
2847 #endif
2848 null_check_receiver(); // null-check, then ignore
2849 Node *addr = argument(1);
2850 addr = new CastX2PNode(addr);
2851 addr = _gvn.transform(addr);
2852 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
2853 flush = _gvn.transform(flush);
2854 set_memory(flush, TypeRawPtr::BOTTOM);
2855 return true;
2856 }
2857
2858 //----------------------------inline_unsafe_writeback0-------------------------
2859 // public native void Unsafe.writeback0(long address)
2860 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
2861 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
2862 return false;
2863 }
2864 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
2865 return false;
2866 }
2867 #ifndef PRODUCT
2868 assert(Matcher::has_match_rule(Op_CacheWB),
2869 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
2870 : "found match rule for CacheWBPostSync but not CacheWB"));
2871
2872 #endif
2873 null_check_receiver(); // null-check, then ignore
2874 Node *sync;
2875 if (is_pre) {
2876 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2877 } else {
2878 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2879 }
2880 sync = _gvn.transform(sync);
2881 set_memory(sync, TypeRawPtr::BOTTOM);
2882 return true;
2883 }
2884
2885 //----------------------------inline_unsafe_allocate---------------------------
2886 // public native Object Unsafe.allocateInstance(Class<?> cls);
2887 bool LibraryCallKit::inline_unsafe_allocate() {
2888
2889 #if INCLUDE_JVMTI
2890 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
2891 return false;
2892 }
2893 #endif //INCLUDE_JVMTI
2894
2895 if (callee()->is_static()) return false; // caller must have the capability!
2896
2897 null_check_receiver(); // null-check, then ignore
2898 Node* cls = null_check(argument(1));
2899 if (stopped()) return true;
2900
2901 Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
2902 kls = null_check(kls);
2903 if (stopped()) return true; // argument was like int.class
2904
2905 #if INCLUDE_JVMTI
2906 // Don't try to access new allocated obj in the intrinsic.
2907 // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
2908 // Deoptimize and allocate in interpreter instead.
2909 Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
2910 Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
2911 Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
2912 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2913 {
2914 BuildCutout unless(this, tst, PROB_MAX);
2915 uncommon_trap(Deoptimization::Reason_intrinsic,
2916 Deoptimization::Action_make_not_entrant);
2917 }
2918 if (stopped()) {
2919 return true;
2920 }
2921 #endif //INCLUDE_JVMTI
2922
2923 Node* test = nullptr;
2924 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2925 // Note: The argument might still be an illegal value like
2926 // Serializable.class or Object[].class. The runtime will handle it.
2927 // But we must make an explicit check for initialization.
2928 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
2929 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2930 // can generate code to load it as unsigned byte.
2931 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2932 Node* bits = intcon(InstanceKlass::fully_initialized);
2933 test = _gvn.transform(new SubINode(inst, bits));
2934 // The 'test' is non-zero if we need to take a slow path.
2935 }
2936
2937 Node* obj = new_instance(kls, test);
2938 set_result(obj);
2939 return true;
2940 }
2941
2942 //------------------------inline_native_time_funcs--------------
2943 // inline code for System.currentTimeMillis() and System.nanoTime()
2944 // these have the same type and signature
2945 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2946 const TypeFunc* tf = OptoRuntime::void_long_Type();
2947 const TypePtr* no_memory_effects = nullptr;
2948 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2949 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2950 #ifdef ASSERT
2951 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2952 assert(value_top == top(), "second value must be top");
2953 #endif
2954 set_result(value);
2955 return true;
2956 }
2957
2958 //--------------------inline_native_vthread_start_transition--------------------
2959 // inline void startTransition(boolean is_mount);
2960 // inline void startFinalTransition();
2961 // Pseudocode of implementation:
2962 //
2963 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
2964 // carrier->set_is_in_vthread_transition(true);
2965 // OrderAccess::storeload();
2966 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
2967 // + global_vthread_transition_disable_count();
2968 // if (disable_requests > 0) {
2969 // slow path: runtime call
2970 // }
2971 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
2972 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
2973 IdealKit ideal(this);
2974
2975 Node* thread = ideal.thread();
2976 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
2977 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
2978 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
2979 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
2980 insert_mem_bar(Op_MemBarStoreLoad);
2981 ideal.sync_kit(this);
2982
2983 Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
2984 Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
2985 Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
2986 const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
2987 Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
2988 Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
2989
2990 ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
2991 sync_kit(ideal);
2992 Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
2993 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
2994 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
2995 ideal.sync_kit(this);
2996 }
2997 ideal.end_if();
2998
2999 final_sync(ideal);
3000 return true;
3001 }
3002
3003 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3004 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3005 IdealKit ideal(this);
3006
3007 Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3008 Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3009
3010 ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3011 sync_kit(ideal);
3012 Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3013 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3014 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3015 ideal.sync_kit(this);
3016 } ideal.else_(); {
3017 Node* thread = ideal.thread();
3018 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3019 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3020
3021 sync_kit(ideal);
3022 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3023 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3024 ideal.sync_kit(this);
3025 } ideal.end_if();
3026
3027 final_sync(ideal);
3028 return true;
3029 }
3030
3031 #if INCLUDE_JVMTI
3032
3033 // Always update the is_disable_suspend bit.
3034 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3035 if (!DoJVMTIVirtualThreadTransitions) {
3036 return true;
3037 }
3038 IdealKit ideal(this);
3039
3040 {
3041 // unconditionally update the is_disable_suspend bit in current JavaThread
3042 Node* thread = ideal.thread();
3043 Node* arg = argument(0); // argument for notification
3044 Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3045 const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3046
3047 sync_kit(ideal);
3048 access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3049 ideal.sync_kit(this);
3050 }
3051 final_sync(ideal);
3052
3053 return true;
3054 }
3055
3056 #endif // INCLUDE_JVMTI
3057
3058 #ifdef JFR_HAVE_INTRINSICS
3059
3060 /**
3061 * if oop->klass != null
3062 * // normal class
3063 * epoch = _epoch_state ? 2 : 1
3064 * if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3065 * ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3066 * }
3067 * id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3068 * else
3069 * // primitive class
3070 * if oop->array_klass != null
3071 * id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3072 * else
3073 * id = LAST_TYPE_ID + 1 // void class path
3074 * if (!signaled)
3075 * signaled = true
3076 */
3077 bool LibraryCallKit::inline_native_classID() {
3078 Node* cls = argument(0);
3079
3080 IdealKit ideal(this);
3081 #define __ ideal.
3082 IdealVariable result(ideal); __ declarations_done();
3083 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3084 basic_plus_adr(cls, java_lang_Class::klass_offset()),
3085 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3086
3087
3088 __ if_then(kls, BoolTest::ne, null()); {
3089 Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3090 Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3091
3092 Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3093 Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3094 epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3095 Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3096 mask = _gvn.transform(new OrLNode(mask, epoch));
3097 Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3098
3099 float unlikely = PROB_UNLIKELY(0.999);
3100 __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3101 sync_kit(ideal);
3102 make_runtime_call(RC_LEAF,
3103 OptoRuntime::class_id_load_barrier_Type(),
3104 CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3105 "class id load barrier",
3106 TypePtr::BOTTOM,
3107 kls);
3108 ideal.sync_kit(this);
3109 } __ end_if();
3110
3111 ideal.set(result, _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3112 } __ else_(); {
3113 Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3114 basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3115 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3116 __ if_then(array_kls, BoolTest::ne, null()); {
3117 Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3118 Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3119 Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3120 ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3121 } __ else_(); {
3122 // void class case
3123 ideal.set(result, longcon(LAST_TYPE_ID + 1));
3124 } __ end_if();
3125
3126 Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3127 Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3128 __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3129 ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3130 } __ end_if();
3131 } __ end_if();
3132
3133 final_sync(ideal);
3134 set_result(ideal.value(result));
3135 #undef __
3136 return true;
3137 }
3138
3139 //------------------------inline_native_jvm_commit------------------
3140 bool LibraryCallKit::inline_native_jvm_commit() {
3141 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3142
3143 // Save input memory and i_o state.
3144 Node* input_memory_state = reset_memory();
3145 set_all_memory(input_memory_state);
3146 Node* input_io_state = i_o();
3147
3148 // TLS.
3149 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3150 // Jfr java buffer.
3151 Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3152 Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3153 Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3154
3155 // Load the current value of the notified field in the JfrThreadLocal.
3156 Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3157 Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3158
3159 // Test for notification.
3160 Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3161 Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3162 IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3163
3164 // True branch, is notified.
3165 Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3166 set_control(is_notified);
3167
3168 // Reset notified state.
3169 store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3170 Node* notified_reset_memory = reset_memory();
3171
3172 // 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.
3173 Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3174 // Convert the machine-word to a long.
3175 Node* current_pos = ConvX2L(current_pos_X);
3176
3177 // False branch, not notified.
3178 Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3179 set_control(not_notified);
3180 set_all_memory(input_memory_state);
3181
3182 // Arg is the next position as a long.
3183 Node* arg = argument(0);
3184 // Convert long to machine-word.
3185 Node* next_pos_X = ConvL2X(arg);
3186
3187 // Store the next_position to the underlying jfr java buffer.
3188 store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3189
3190 Node* commit_memory = reset_memory();
3191 set_all_memory(commit_memory);
3192
3193 // 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.
3194 Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3195 Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3196 Node* lease_constant = _gvn.intcon(4);
3197
3198 // And flags with lease constant.
3199 Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3200
3201 // Branch on lease to conditionalize returning the leased java buffer.
3202 Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3203 Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3204 IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3205
3206 // False branch, not a lease.
3207 Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3208
3209 // True branch, is lease.
3210 Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3211 set_control(is_lease);
3212
3213 // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3214 Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3215 OptoRuntime::void_void_Type(),
3216 SharedRuntime::jfr_return_lease(),
3217 "return_lease", TypePtr::BOTTOM);
3218 Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3219
3220 RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3221 record_for_igvn(lease_compare_rgn);
3222 PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3223 record_for_igvn(lease_compare_mem);
3224 PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3225 record_for_igvn(lease_compare_io);
3226 PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3227 record_for_igvn(lease_result_value);
3228
3229 // Update control and phi nodes.
3230 lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3231 lease_compare_rgn->init_req(_false_path, not_lease);
3232
3233 lease_compare_mem->init_req(_true_path, reset_memory());
3234 lease_compare_mem->init_req(_false_path, commit_memory);
3235
3236 lease_compare_io->init_req(_true_path, i_o());
3237 lease_compare_io->init_req(_false_path, input_io_state);
3238
3239 lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3240 lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3241
3242 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3243 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3244 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3245 PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3246
3247 // Update control and phi nodes.
3248 result_rgn->init_req(_true_path, is_notified);
3249 result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3250
3251 result_mem->init_req(_true_path, notified_reset_memory);
3252 result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3253
3254 result_io->init_req(_true_path, input_io_state);
3255 result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3256
3257 result_value->init_req(_true_path, current_pos);
3258 result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3259
3260 // Set output state.
3261 set_control(_gvn.transform(result_rgn));
3262 set_all_memory(_gvn.transform(result_mem));
3263 set_i_o(_gvn.transform(result_io));
3264 set_result(result_rgn, result_value);
3265 return true;
3266 }
3267
3268 /*
3269 * The intrinsic is a model of this pseudo-code:
3270 *
3271 * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3272 * jobject h_event_writer = tl->java_event_writer();
3273 * if (h_event_writer == nullptr) {
3274 * return nullptr;
3275 * }
3276 * oop threadObj = Thread::threadObj();
3277 * oop vthread = java_lang_Thread::vthread(threadObj);
3278 * traceid tid;
3279 * bool pinVirtualThread;
3280 * bool excluded;
3281 * if (vthread != threadObj) { // i.e. current thread is virtual
3282 * tid = java_lang_Thread::tid(vthread);
3283 * u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3284 * pinVirtualThread = VMContinuations;
3285 * excluded = vthread_epoch_raw & excluded_mask;
3286 * if (!excluded) {
3287 * traceid current_epoch = JfrTraceIdEpoch::current_generation();
3288 * u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3289 * if (vthread_epoch != current_epoch) {
3290 * write_checkpoint();
3291 * }
3292 * }
3293 * } else {
3294 * tid = java_lang_Thread::tid(threadObj);
3295 * u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3296 * pinVirtualThread = false;
3297 * excluded = thread_epoch_raw & excluded_mask;
3298 * }
3299 * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3300 * traceid tid_in_event_writer = getField(event_writer, "threadID");
3301 * if (tid_in_event_writer != tid) {
3302 * setField(event_writer, "pinVirtualThread", pinVirtualThread);
3303 * setField(event_writer, "excluded", excluded);
3304 * setField(event_writer, "threadID", tid);
3305 * }
3306 * return event_writer
3307 */
3308 bool LibraryCallKit::inline_native_getEventWriter() {
3309 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3310
3311 // Save input memory and i_o state.
3312 Node* input_memory_state = reset_memory();
3313 set_all_memory(input_memory_state);
3314 Node* input_io_state = i_o();
3315
3316 // The most significant bit of the u2 is used to denote thread exclusion
3317 Node* excluded_shift = _gvn.intcon(15);
3318 Node* excluded_mask = _gvn.intcon(1 << 15);
3319 // The epoch generation is the range [1-32767]
3320 Node* epoch_mask = _gvn.intcon(32767);
3321
3322 // TLS
3323 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3324
3325 // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3326 Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3327
3328 // Load the eventwriter jobject handle.
3329 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3330
3331 // Null check the jobject handle.
3332 Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3333 Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3334 IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3335
3336 // False path, jobj is null.
3337 Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3338
3339 // True path, jobj is not null.
3340 Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3341
3342 set_control(jobj_is_not_null);
3343
3344 // Load the threadObj for the CarrierThread.
3345 Node* threadObj = generate_current_thread(tls_ptr);
3346
3347 // Load the vthread.
3348 Node* vthread = generate_virtual_thread(tls_ptr);
3349
3350 // If vthread != threadObj, this is a virtual thread.
3351 Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3352 Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3353 IfNode* iff_vthread_not_equal_threadObj =
3354 create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3355
3356 // False branch, fallback to threadObj.
3357 Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3358 set_control(vthread_equal_threadObj);
3359
3360 // Load the tid field from the vthread object.
3361 Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3362
3363 // Load the raw epoch value from the threadObj.
3364 Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3365 Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3366 _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3367 TypeInt::CHAR, T_CHAR,
3368 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3369
3370 // Mask off the excluded information from the epoch.
3371 Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3372
3373 // True branch, this is a virtual thread.
3374 Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3375 set_control(vthread_not_equal_threadObj);
3376
3377 // Load the tid field from the vthread object.
3378 Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3379
3380 // Continuation support determines if a virtual thread should be pinned.
3381 Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3382 Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3383
3384 // Load the raw epoch value from the vthread.
3385 Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3386 Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3387 TypeInt::CHAR, T_CHAR,
3388 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3389
3390 // Mask off the excluded information from the epoch.
3391 Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3392
3393 // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3394 Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3395 Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3396 IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3397
3398 // False branch, vthread is excluded, no need to write epoch info.
3399 Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3400
3401 // True branch, vthread is included, update epoch info.
3402 Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3403 set_control(included);
3404
3405 // Get epoch value.
3406 Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3407
3408 // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3409 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3410 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3411
3412 // Compare the epoch in the vthread to the current epoch generation.
3413 Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3414 Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3415 IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3416
3417 // False path, epoch is equal, checkpoint information is valid.
3418 Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3419
3420 // True path, epoch is not equal, write a checkpoint for the vthread.
3421 Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3422
3423 set_control(epoch_is_not_equal);
3424
3425 // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3426 // The call also updates the native thread local thread id and the vthread with the current epoch.
3427 Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3428 OptoRuntime::jfr_write_checkpoint_Type(),
3429 SharedRuntime::jfr_write_checkpoint(),
3430 "write_checkpoint", TypePtr::BOTTOM);
3431 Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3432
3433 // vthread epoch != current epoch
3434 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3435 record_for_igvn(epoch_compare_rgn);
3436 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3437 record_for_igvn(epoch_compare_mem);
3438 PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3439 record_for_igvn(epoch_compare_io);
3440
3441 // Update control and phi nodes.
3442 epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3443 epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3444 epoch_compare_mem->init_req(_true_path, reset_memory());
3445 epoch_compare_mem->init_req(_false_path, input_memory_state);
3446 epoch_compare_io->init_req(_true_path, i_o());
3447 epoch_compare_io->init_req(_false_path, input_io_state);
3448
3449 // excluded != true
3450 RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3451 record_for_igvn(exclude_compare_rgn);
3452 PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3453 record_for_igvn(exclude_compare_mem);
3454 PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3455 record_for_igvn(exclude_compare_io);
3456
3457 // Update control and phi nodes.
3458 exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3459 exclude_compare_rgn->init_req(_false_path, excluded);
3460 exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3461 exclude_compare_mem->init_req(_false_path, input_memory_state);
3462 exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3463 exclude_compare_io->init_req(_false_path, input_io_state);
3464
3465 // vthread != threadObj
3466 RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3467 record_for_igvn(vthread_compare_rgn);
3468 PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3469 PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3470 record_for_igvn(vthread_compare_io);
3471 PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3472 record_for_igvn(tid);
3473 PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3474 record_for_igvn(exclusion);
3475 PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3476 record_for_igvn(pinVirtualThread);
3477
3478 // Update control and phi nodes.
3479 vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3480 vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3481 vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3482 vthread_compare_mem->init_req(_false_path, input_memory_state);
3483 vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3484 vthread_compare_io->init_req(_false_path, input_io_state);
3485 tid->init_req(_true_path, vthread_tid);
3486 tid->init_req(_false_path, thread_obj_tid);
3487 exclusion->init_req(_true_path, vthread_is_excluded);
3488 exclusion->init_req(_false_path, threadObj_is_excluded);
3489 pinVirtualThread->init_req(_true_path, continuation_support);
3490 pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3491
3492 // Update branch state.
3493 set_control(_gvn.transform(vthread_compare_rgn));
3494 set_all_memory(_gvn.transform(vthread_compare_mem));
3495 set_i_o(_gvn.transform(vthread_compare_io));
3496
3497 // Load the event writer oop by dereferencing the jobject handle.
3498 ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3499 assert(klass_EventWriter->is_loaded(), "invariant");
3500 ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3501 const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3502 const TypeOopPtr* const xtype = aklass->as_instance_type();
3503 Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3504 Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3505
3506 // Load the current thread id from the event writer object.
3507 Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3508 // Get the field offset to, conditionally, store an updated tid value later.
3509 Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3510 // Get the field offset to, conditionally, store an updated exclusion value later.
3511 Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3512 // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3513 Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3514
3515 RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3516 record_for_igvn(event_writer_tid_compare_rgn);
3517 PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3518 record_for_igvn(event_writer_tid_compare_mem);
3519 PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3520 record_for_igvn(event_writer_tid_compare_io);
3521
3522 // Compare the current tid from the thread object to what is currently stored in the event writer object.
3523 Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3524 Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3525 IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3526
3527 // False path, tids are the same.
3528 Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3529
3530 // True path, tid is not equal, need to update the tid in the event writer.
3531 Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3532 record_for_igvn(tid_is_not_equal);
3533
3534 // Store the pin state to the event writer.
3535 store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3536
3537 // Store the exclusion state to the event writer.
3538 Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3539 store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3540
3541 // Store the tid to the event writer.
3542 store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3543
3544 // Update control and phi nodes.
3545 event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3546 event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3547 event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3548 event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3549 event_writer_tid_compare_io->init_req(_true_path, i_o());
3550 event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3551
3552 // Result of top level CFG, Memory, IO and Value.
3553 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3554 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3555 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3556 PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3557
3558 // Result control.
3559 result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3560 result_rgn->init_req(_false_path, jobj_is_null);
3561
3562 // Result memory.
3563 result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3564 result_mem->init_req(_false_path, input_memory_state);
3565
3566 // Result IO.
3567 result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3568 result_io->init_req(_false_path, input_io_state);
3569
3570 // Result value.
3571 result_value->init_req(_true_path, event_writer); // return event writer oop
3572 result_value->init_req(_false_path, null()); // return null
3573
3574 // Set output state.
3575 set_control(_gvn.transform(result_rgn));
3576 set_all_memory(_gvn.transform(result_mem));
3577 set_i_o(_gvn.transform(result_io));
3578 set_result(result_rgn, result_value);
3579 return true;
3580 }
3581
3582 /*
3583 * The intrinsic is a model of this pseudo-code:
3584 *
3585 * JfrThreadLocal* const tl = thread->jfr_thread_local();
3586 * if (carrierThread != thread) { // is virtual thread
3587 * const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3588 * bool excluded = vthread_epoch_raw & excluded_mask;
3589 * AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3590 * AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3591 * if (!excluded) {
3592 * const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3593 * AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3594 * }
3595 * AtomicAccess::release_store(&tl->_vthread, true);
3596 * return;
3597 * }
3598 * AtomicAccess::release_store(&tl->_vthread, false);
3599 */
3600 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3601 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3602
3603 Node* input_memory_state = reset_memory();
3604 set_all_memory(input_memory_state);
3605
3606 // The most significant bit of the u2 is used to denote thread exclusion
3607 Node* excluded_mask = _gvn.intcon(1 << 15);
3608 // The epoch generation is the range [1-32767]
3609 Node* epoch_mask = _gvn.intcon(32767);
3610
3611 Node* const carrierThread = generate_current_thread(jt);
3612 // If thread != carrierThread, this is a virtual thread.
3613 Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3614 Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3615 IfNode* iff_thread_not_equal_carrierThread =
3616 create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3617
3618 Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3619
3620 // False branch, is carrierThread.
3621 Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3622 // Store release
3623 Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3624
3625 set_all_memory(input_memory_state);
3626
3627 // True branch, is virtual thread.
3628 Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
3629 set_control(thread_not_equal_carrierThread);
3630
3631 // Load the raw epoch value from the vthread.
3632 Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
3633 Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
3634 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3635
3636 // Mask off the excluded information from the epoch.
3637 Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
3638
3639 // Load the tid field from the thread.
3640 Node* tid = load_field_from_object(thread, "tid", "J");
3641
3642 // Store the vthread tid to the jfr thread local.
3643 Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
3644 Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
3645
3646 // Branch is_excluded to conditionalize updating the epoch .
3647 Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
3648 Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
3649 IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
3650
3651 // True branch, vthread is excluded, no need to write epoch info.
3652 Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
3653 set_control(excluded);
3654 Node* vthread_is_excluded = _gvn.intcon(1);
3655
3656 // False branch, vthread is included, update epoch info.
3657 Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
3658 set_control(included);
3659 Node* vthread_is_included = _gvn.intcon(0);
3660
3661 // Get epoch value.
3662 Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
3663
3664 // Store the vthread epoch to the jfr thread local.
3665 Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
3666 Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
3667
3668 RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
3669 record_for_igvn(excluded_rgn);
3670 PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
3671 record_for_igvn(excluded_mem);
3672 PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
3673 record_for_igvn(exclusion);
3674
3675 // Merge the excluded control and memory.
3676 excluded_rgn->init_req(_true_path, excluded);
3677 excluded_rgn->init_req(_false_path, included);
3678 excluded_mem->init_req(_true_path, tid_memory);
3679 excluded_mem->init_req(_false_path, included_memory);
3680 exclusion->init_req(_true_path, vthread_is_excluded);
3681 exclusion->init_req(_false_path, vthread_is_included);
3682
3683 // Set intermediate state.
3684 set_control(_gvn.transform(excluded_rgn));
3685 set_all_memory(excluded_mem);
3686
3687 // Store the vthread exclusion state to the jfr thread local.
3688 Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
3689 store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
3690
3691 // Store release
3692 Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
3693
3694 RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
3695 record_for_igvn(thread_compare_rgn);
3696 PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3697 record_for_igvn(thread_compare_mem);
3698 PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
3699 record_for_igvn(vthread);
3700
3701 // Merge the thread_compare control and memory.
3702 thread_compare_rgn->init_req(_true_path, control());
3703 thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
3704 thread_compare_mem->init_req(_true_path, vthread_true_memory);
3705 thread_compare_mem->init_req(_false_path, vthread_false_memory);
3706
3707 // Set output state.
3708 set_control(_gvn.transform(thread_compare_rgn));
3709 set_all_memory(_gvn.transform(thread_compare_mem));
3710 }
3711
3712 //------------------------inline_native_try_update_epoch------------------
3713 //
3714 // The generated code is a function of the argument type.
3715 //
3716 bool LibraryCallKit::inline_native_try_update_epoch() {
3717 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3718
3719 // Save input memory.
3720 Node* input_memory_state = reset_memory();
3721 set_all_memory(input_memory_state);
3722
3723 // Argument is an oop whose class has an injected instance field,
3724 // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
3725 Node* oop = argument(0);
3726 const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
3727 assert(tinst != nullptr, "oop is null");
3728 assert(tinst->is_loaded(), "klass is not loaded");
3729 ciInstanceKlass* const ik = tinst->instance_klass();
3730
3731 ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
3732 ciSymbol::make("I"));
3733
3734 assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
3735
3736 const int jfr_epoch_field_offset = field->offset_in_bytes();
3737 Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
3738 const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
3739 const int alias_idx = C->get_alias_index(adr_type);
3740 BasicType bt = field->layout_type();
3741 const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
3742
3743 // Load the epoch value from the oop.
3744 Node* oop_epoch = access_load_at(oop,
3745 oop_epoch_field_offset,
3746 adr_type, oop_epoch_field_type,
3747 bt, IN_HEAP | MO_UNORDERED);
3748
3749 // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3750 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3751 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3752
3753 // Compare the epoch in the oop against the current JFR epoch generation.
3754 Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
3755 Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
3756 IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
3757
3758 // True path.
3759 Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
3760
3761 // False path.
3762 Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
3763
3764 set_control(_gvn.transform(epochs_are_not_equal));
3765
3766 // Attempt to cas the current JFR epoch generation into the oop epoch field.
3767 DecoratorSet decorators = IN_HEAP;
3768 decorators |= mo_decorator_for_access_kind(Volatile);
3769
3770 Node* result = access_atomic_cmpxchg_val_at(oop,
3771 oop_epoch_field_offset,
3772 adr_type, alias_idx,
3773 oop_epoch, // expected value
3774 current_epoch_generation, // new value
3775 oop_epoch_field_type,
3776 bt,
3777 decorators);
3778
3779 // Compare the result of the cas operation to the expected value.
3780 Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
3781 Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
3782 IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
3783
3784 // True path.
3785 Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
3786
3787 // False path.
3788 Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
3789
3790 // Cas result region and phi nodes.
3791 RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
3792 record_for_igvn(cas_operation_rgn);
3793 PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
3794 record_for_igvn(cas_operation_mem);
3795 PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
3796 record_for_igvn(cas_result);
3797
3798 cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
3799 cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
3800 cas_operation_mem->init_req(_true_path, reset_memory());
3801 cas_operation_mem->init_req(_false_path, input_memory_state);
3802 cas_result->init_req(_true_path, _gvn.intcon(1));
3803 cas_result->init_req(_false_path, _gvn.intcon(0));
3804
3805 // Epoch compare region and phi nodes.
3806 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3807 record_for_igvn(epoch_compare_rgn);
3808 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3809 record_for_igvn(epoch_compare_mem);
3810 PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
3811 record_for_igvn(result_value);
3812
3813 epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
3814 epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
3815 epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
3816 epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
3817 result_value->init_req(_true_path, _gvn.intcon(0));
3818 result_value->init_req(_false_path, _gvn.transform(cas_result));
3819
3820 // Set output state.
3821 set_result(epoch_compare_rgn, result_value);
3822 set_all_memory(_gvn.transform(epoch_compare_mem));
3823
3824 return true;
3825 }
3826
3827 #endif // JFR_HAVE_INTRINSICS
3828
3829 //------------------------inline_native_currentCarrierThread------------------
3830 bool LibraryCallKit::inline_native_currentCarrierThread() {
3831 Node* junk = nullptr;
3832 set_result(generate_current_thread(junk));
3833 return true;
3834 }
3835
3836 //------------------------inline_native_currentThread------------------
3837 bool LibraryCallKit::inline_native_currentThread() {
3838 Node* junk = nullptr;
3839 set_result(generate_virtual_thread(junk));
3840 return true;
3841 }
3842
3843 //------------------------inline_native_setVthread------------------
3844 bool LibraryCallKit::inline_native_setCurrentThread() {
3845 assert(C->method()->changes_current_thread(),
3846 "method changes current Thread but is not annotated ChangesCurrentThread");
3847 Node* arr = argument(1);
3848 Node* thread = _gvn.transform(new ThreadLocalNode());
3849 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
3850 Node* thread_obj_handle
3851 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3852 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3853 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3854
3855 // Change the _monitor_owner_id of the JavaThread
3856 Node* tid = load_field_from_object(arr, "tid", "J");
3857 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3858 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3859
3860 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3861 return true;
3862 }
3863
3864 const Type* LibraryCallKit::scopedValueCache_type() {
3865 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3866 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3867 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3868
3869 // Because we create the scopedValue cache lazily we have to make the
3870 // type of the result BotPTR.
3871 bool xk = etype->klass_is_exact();
3872 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3873 return objects_type;
3874 }
3875
3876 Node* LibraryCallKit::scopedValueCache_helper() {
3877 Node* thread = _gvn.transform(new ThreadLocalNode());
3878 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
3879 // We cannot use immutable_memory() because we might flip onto a
3880 // different carrier thread, at which point we'll need to use that
3881 // carrier thread's cache.
3882 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3883 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3884 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3885 }
3886
3887 //------------------------inline_native_scopedValueCache------------------
3888 bool LibraryCallKit::inline_native_scopedValueCache() {
3889 Node* cache_obj_handle = scopedValueCache_helper();
3890 const Type* objects_type = scopedValueCache_type();
3891 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3892
3893 return true;
3894 }
3895
3896 //------------------------inline_native_setScopedValueCache------------------
3897 bool LibraryCallKit::inline_native_setScopedValueCache() {
3898 Node* arr = argument(0);
3899 Node* cache_obj_handle = scopedValueCache_helper();
3900 const Type* objects_type = scopedValueCache_type();
3901
3902 const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
3903 access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
3904
3905 return true;
3906 }
3907
3908 //------------------------inline_native_Continuation_pin and unpin-----------
3909
3910 // Shared implementation routine for both pin and unpin.
3911 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
3912 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3913
3914 // Save input memory.
3915 Node* input_memory_state = reset_memory();
3916 set_all_memory(input_memory_state);
3917
3918 // TLS
3919 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3920 Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
3921 Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
3922
3923 // Null check the last continuation object.
3924 Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
3925 Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
3926 IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3927
3928 // False path, last continuation is null.
3929 Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
3930
3931 // True path, last continuation is not null.
3932 Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
3933
3934 set_control(continuation_is_not_null);
3935
3936 // Load the pin count from the last continuation.
3937 Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
3938 Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
3939
3940 // The loaded pin count is compared against a context specific rhs for over/underflow detection.
3941 Node* pin_count_rhs;
3942 if (unpin) {
3943 pin_count_rhs = _gvn.intcon(0);
3944 } else {
3945 pin_count_rhs = _gvn.intcon(UINT32_MAX);
3946 }
3947 Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
3948 Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
3949 IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
3950
3951 // True branch, pin count over/underflow.
3952 Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
3953 {
3954 // Trap (but not deoptimize (Action_none)) and continue in the interpreter
3955 // which will throw IllegalStateException for pin count over/underflow.
3956 // No memory changed so far - we can use memory create by reset_memory()
3957 // at the beginning of this intrinsic. No need to call reset_memory() again.
3958 PreserveJVMState pjvms(this);
3959 set_control(pin_count_over_underflow);
3960 uncommon_trap(Deoptimization::Reason_intrinsic,
3961 Deoptimization::Action_none);
3962 assert(stopped(), "invariant");
3963 }
3964
3965 // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
3966 Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
3967 set_control(valid_pin_count);
3968
3969 Node* next_pin_count;
3970 if (unpin) {
3971 next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
3972 } else {
3973 next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
3974 }
3975
3976 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3977
3978 // Result of top level CFG and Memory.
3979 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3980 record_for_igvn(result_rgn);
3981 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3982 record_for_igvn(result_mem);
3983
3984 result_rgn->init_req(_true_path, valid_pin_count);
3985 result_rgn->init_req(_false_path, continuation_is_null);
3986 result_mem->init_req(_true_path, reset_memory());
3987 result_mem->init_req(_false_path, input_memory_state);
3988
3989 // Set output state.
3990 set_control(_gvn.transform(result_rgn));
3991 set_all_memory(_gvn.transform(result_mem));
3992
3993 return true;
3994 }
3995
3996 //---------------------------load_mirror_from_klass----------------------------
3997 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3998 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3999 Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4000 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4001 // mirror = ((OopHandle)mirror)->resolve();
4002 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4003 }
4004
4005 //-----------------------load_klass_from_mirror_common-------------------------
4006 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4007 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4008 // and branch to the given path on the region.
4009 // If never_see_null, take an uncommon trap on null, so we can optimistically
4010 // compile for the non-null case.
4011 // If the region is null, force never_see_null = true.
4012 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4013 bool never_see_null,
4014 RegionNode* region,
4015 int null_path,
4016 int offset) {
4017 if (region == nullptr) never_see_null = true;
4018 Node* p = basic_plus_adr(mirror, offset);
4019 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4020 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4021 Node* null_ctl = top();
4022 kls = null_check_oop(kls, &null_ctl, never_see_null);
4023 if (region != nullptr) {
4024 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4025 region->init_req(null_path, null_ctl);
4026 } else {
4027 assert(null_ctl == top(), "no loose ends");
4028 }
4029 return kls;
4030 }
4031
4032 //--------------------(inline_native_Class_query helpers)---------------------
4033 // Use this for JVM_ACC_INTERFACE.
4034 // Fall through if (mods & mask) == bits, take the guard otherwise.
4035 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4036 ByteSize offset, const Type* type, BasicType bt) {
4037 // Branch around if the given klass has the given modifier bit set.
4038 // Like generate_guard, adds a new path onto the region.
4039 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4040 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4041 Node* mask = intcon(modifier_mask);
4042 Node* bits = intcon(modifier_bits);
4043 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4044 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4045 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4046 return generate_fair_guard(bol, region);
4047 }
4048 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4049 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4050 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4051 }
4052
4053 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4054 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4055 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4056 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4057 }
4058
4059 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4060 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4061 }
4062
4063 //-------------------------inline_native_Class_query-------------------
4064 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4065 const Type* return_type = TypeInt::BOOL;
4066 Node* prim_return_value = top(); // what happens if it's a primitive class?
4067 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4068 bool expect_prim = false; // most of these guys expect to work on refs
4069
4070 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4071
4072 Node* mirror = argument(0);
4073 Node* obj = top();
4074
4075 switch (id) {
4076 case vmIntrinsics::_isInstance:
4077 // nothing is an instance of a primitive type
4078 prim_return_value = intcon(0);
4079 obj = argument(1);
4080 break;
4081 case vmIntrinsics::_isHidden:
4082 prim_return_value = intcon(0);
4083 break;
4084 case vmIntrinsics::_getSuperclass:
4085 prim_return_value = null();
4086 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4087 break;
4088 default:
4089 fatal_unexpected_iid(id);
4090 break;
4091 }
4092
4093 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4094 if (mirror_con == nullptr) return false; // cannot happen?
4095
4096 #ifndef PRODUCT
4097 if (C->print_intrinsics() || C->print_inlining()) {
4098 ciType* k = mirror_con->java_mirror_type();
4099 if (k) {
4100 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4101 k->print_name();
4102 tty->cr();
4103 }
4104 }
4105 #endif
4106
4107 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4108 RegionNode* region = new RegionNode(PATH_LIMIT);
4109 record_for_igvn(region);
4110 PhiNode* phi = new PhiNode(region, return_type);
4111
4112 // The mirror will never be null of Reflection.getClassAccessFlags, however
4113 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4114 // if it is. See bug 4774291.
4115
4116 // For Reflection.getClassAccessFlags(), the null check occurs in
4117 // the wrong place; see inline_unsafe_access(), above, for a similar
4118 // situation.
4119 mirror = null_check(mirror);
4120 // If mirror or obj is dead, only null-path is taken.
4121 if (stopped()) return true;
4122
4123 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
4124
4125 // Now load the mirror's klass metaobject, and null-check it.
4126 // Side-effects region with the control path if the klass is null.
4127 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4128 // If kls is null, we have a primitive mirror.
4129 phi->init_req(_prim_path, prim_return_value);
4130 if (stopped()) { set_result(region, phi); return true; }
4131 bool safe_for_replace = (region->in(_prim_path) == top());
4132
4133 Node* p; // handy temp
4134 Node* null_ctl;
4135
4136 // Now that we have the non-null klass, we can perform the real query.
4137 // For constant classes, the query will constant-fold in LoadNode::Value.
4138 Node* query_value = top();
4139 switch (id) {
4140 case vmIntrinsics::_isInstance:
4141 // nothing is an instance of a primitive type
4142 query_value = gen_instanceof(obj, kls, safe_for_replace);
4143 break;
4144
4145 case vmIntrinsics::_isHidden:
4146 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4147 if (generate_hidden_class_guard(kls, region) != nullptr)
4148 // A guard was added. If the guard is taken, it was an hidden class.
4149 phi->add_req(intcon(1));
4150 // If we fall through, it's a plain class.
4151 query_value = intcon(0);
4152 break;
4153
4154
4155 case vmIntrinsics::_getSuperclass:
4156 // The rules here are somewhat unfortunate, but we can still do better
4157 // with random logic than with a JNI call.
4158 // Interfaces store null or Object as _super, but must report null.
4159 // Arrays store an intermediate super as _super, but must report Object.
4160 // Other types can report the actual _super.
4161 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4162 if (generate_array_guard(kls, region) != nullptr) {
4163 // A guard was added. If the guard is taken, it was an array.
4164 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4165 }
4166 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4167 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4168 if (generate_interface_guard(kls, region) != nullptr) {
4169 // A guard was added. If the guard is taken, it was an interface.
4170 phi->add_req(null());
4171 }
4172 // If we fall through, it's a plain class. Get its _super.
4173 p = off_heap_plus_addr(kls, in_bytes(Klass::super_offset()));
4174 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4175 null_ctl = top();
4176 kls = null_check_oop(kls, &null_ctl);
4177 if (null_ctl != top()) {
4178 // If the guard is taken, Object.superClass is null (both klass and mirror).
4179 region->add_req(null_ctl);
4180 phi ->add_req(null());
4181 }
4182 if (!stopped()) {
4183 query_value = load_mirror_from_klass(kls);
4184 }
4185 break;
4186
4187 default:
4188 fatal_unexpected_iid(id);
4189 break;
4190 }
4191
4192 // Fall-through is the normal case of a query to a real class.
4193 phi->init_req(1, query_value);
4194 region->init_req(1, control());
4195
4196 C->set_has_split_ifs(true); // Has chance for split-if optimization
4197 set_result(region, phi);
4198 return true;
4199 }
4200
4201 //-------------------------inline_Class_cast-------------------
4202 bool LibraryCallKit::inline_Class_cast() {
4203 Node* mirror = argument(0); // Class
4204 Node* obj = argument(1);
4205 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4206 if (mirror_con == nullptr) {
4207 return false; // dead path (mirror->is_top()).
4208 }
4209 if (obj == nullptr || obj->is_top()) {
4210 return false; // dead path
4211 }
4212 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4213
4214 // First, see if Class.cast() can be folded statically.
4215 // java_mirror_type() returns non-null for compile-time Class constants.
4216 ciType* tm = mirror_con->java_mirror_type();
4217 if (tm != nullptr && tm->is_klass() &&
4218 tp != nullptr) {
4219 if (!tp->is_loaded()) {
4220 // Don't use intrinsic when class is not loaded.
4221 return false;
4222 } else {
4223 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4224 if (static_res == Compile::SSC_always_true) {
4225 // isInstance() is true - fold the code.
4226 set_result(obj);
4227 return true;
4228 } else if (static_res == Compile::SSC_always_false) {
4229 // Don't use intrinsic, have to throw ClassCastException.
4230 // If the reference is null, the non-intrinsic bytecode will
4231 // be optimized appropriately.
4232 return false;
4233 }
4234 }
4235 }
4236
4237 // Bailout intrinsic and do normal inlining if exception path is frequent.
4238 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4239 return false;
4240 }
4241
4242 // Generate dynamic checks.
4243 // Class.cast() is java implementation of _checkcast bytecode.
4244 // Do checkcast (Parse::do_checkcast()) optimizations here.
4245
4246 mirror = null_check(mirror);
4247 // If mirror is dead, only null-path is taken.
4248 if (stopped()) {
4249 return true;
4250 }
4251
4252 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4253 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4254 RegionNode* region = new RegionNode(PATH_LIMIT);
4255 record_for_igvn(region);
4256
4257 // Now load the mirror's klass metaobject, and null-check it.
4258 // If kls is null, we have a primitive mirror and
4259 // nothing is an instance of a primitive type.
4260 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4261
4262 Node* res = top();
4263 if (!stopped()) {
4264 Node* bad_type_ctrl = top();
4265 // Do checkcast optimizations.
4266 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4267 region->init_req(_bad_type_path, bad_type_ctrl);
4268 }
4269 if (region->in(_prim_path) != top() ||
4270 region->in(_bad_type_path) != top()) {
4271 // Let Interpreter throw ClassCastException.
4272 PreserveJVMState pjvms(this);
4273 set_control(_gvn.transform(region));
4274 uncommon_trap(Deoptimization::Reason_intrinsic,
4275 Deoptimization::Action_maybe_recompile);
4276 }
4277 if (!stopped()) {
4278 set_result(res);
4279 }
4280 return true;
4281 }
4282
4283
4284 //--------------------------inline_native_subtype_check------------------------
4285 // This intrinsic takes the JNI calls out of the heart of
4286 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4287 bool LibraryCallKit::inline_native_subtype_check() {
4288 // Pull both arguments off the stack.
4289 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4290 args[0] = argument(0);
4291 args[1] = argument(1);
4292 Node* klasses[2]; // corresponding Klasses: superk, subk
4293 klasses[0] = klasses[1] = top();
4294
4295 enum {
4296 // A full decision tree on {superc is prim, subc is prim}:
4297 _prim_0_path = 1, // {P,N} => false
4298 // {P,P} & superc!=subc => false
4299 _prim_same_path, // {P,P} & superc==subc => true
4300 _prim_1_path, // {N,P} => false
4301 _ref_subtype_path, // {N,N} & subtype check wins => true
4302 _both_ref_path, // {N,N} & subtype check loses => false
4303 PATH_LIMIT
4304 };
4305
4306 RegionNode* region = new RegionNode(PATH_LIMIT);
4307 Node* phi = new PhiNode(region, TypeInt::BOOL);
4308 record_for_igvn(region);
4309
4310 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4311 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4312 int class_klass_offset = java_lang_Class::klass_offset();
4313
4314 // First null-check both mirrors and load each mirror's klass metaobject.
4315 int which_arg;
4316 for (which_arg = 0; which_arg <= 1; which_arg++) {
4317 Node* arg = args[which_arg];
4318 arg = null_check(arg);
4319 if (stopped()) break;
4320 args[which_arg] = arg;
4321
4322 Node* p = basic_plus_adr(arg, class_klass_offset);
4323 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4324 klasses[which_arg] = _gvn.transform(kls);
4325 }
4326
4327 // Having loaded both klasses, test each for null.
4328 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4329 for (which_arg = 0; which_arg <= 1; which_arg++) {
4330 Node* kls = klasses[which_arg];
4331 Node* null_ctl = top();
4332 kls = null_check_oop(kls, &null_ctl, never_see_null);
4333 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4334 region->init_req(prim_path, null_ctl);
4335 if (stopped()) break;
4336 klasses[which_arg] = kls;
4337 }
4338
4339 if (!stopped()) {
4340 // now we have two reference types, in klasses[0..1]
4341 Node* subk = klasses[1]; // the argument to isAssignableFrom
4342 Node* superk = klasses[0]; // the receiver
4343 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4344 // now we have a successful reference subtype check
4345 region->set_req(_ref_subtype_path, control());
4346 }
4347
4348 // If both operands are primitive (both klasses null), then
4349 // we must return true when they are identical primitives.
4350 // It is convenient to test this after the first null klass check.
4351 set_control(region->in(_prim_0_path)); // go back to first null check
4352 if (!stopped()) {
4353 // Since superc is primitive, make a guard for the superc==subc case.
4354 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4355 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4356 generate_guard(bol_eq, region, PROB_FAIR);
4357 if (region->req() == PATH_LIMIT+1) {
4358 // A guard was added. If the added guard is taken, superc==subc.
4359 region->swap_edges(PATH_LIMIT, _prim_same_path);
4360 region->del_req(PATH_LIMIT);
4361 }
4362 region->set_req(_prim_0_path, control()); // Not equal after all.
4363 }
4364
4365 // these are the only paths that produce 'true':
4366 phi->set_req(_prim_same_path, intcon(1));
4367 phi->set_req(_ref_subtype_path, intcon(1));
4368
4369 // pull together the cases:
4370 assert(region->req() == PATH_LIMIT, "sane region");
4371 for (uint i = 1; i < region->req(); i++) {
4372 Node* ctl = region->in(i);
4373 if (ctl == nullptr || ctl == top()) {
4374 region->set_req(i, top());
4375 phi ->set_req(i, top());
4376 } else if (phi->in(i) == nullptr) {
4377 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4378 }
4379 }
4380
4381 set_control(_gvn.transform(region));
4382 set_result(_gvn.transform(phi));
4383 return true;
4384 }
4385
4386 //---------------------generate_array_guard_common------------------------
4387 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4388 bool obj_array, bool not_array, Node** obj) {
4389
4390 if (stopped()) {
4391 return nullptr;
4392 }
4393
4394 // If obj_array/non_array==false/false:
4395 // Branch around if the given klass is in fact an array (either obj or prim).
4396 // If obj_array/non_array==false/true:
4397 // Branch around if the given klass is not an array klass of any kind.
4398 // If obj_array/non_array==true/true:
4399 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4400 // If obj_array/non_array==true/false:
4401 // Branch around if the kls is an oop array (Object[] or subtype)
4402 //
4403 // Like generate_guard, adds a new path onto the region.
4404 jint layout_con = 0;
4405 Node* layout_val = get_layout_helper(kls, layout_con);
4406 if (layout_val == nullptr) {
4407 bool query = (obj_array
4408 ? Klass::layout_helper_is_objArray(layout_con)
4409 : Klass::layout_helper_is_array(layout_con));
4410 if (query == not_array) {
4411 return nullptr; // never a branch
4412 } else { // always a branch
4413 Node* always_branch = control();
4414 if (region != nullptr)
4415 region->add_req(always_branch);
4416 set_control(top());
4417 return always_branch;
4418 }
4419 }
4420 // Now test the correct condition.
4421 jint nval = (obj_array
4422 ? (jint)(Klass::_lh_array_tag_type_value
4423 << Klass::_lh_array_tag_shift)
4424 : Klass::_lh_neutral_value);
4425 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4426 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4427 // invert the test if we are looking for a non-array
4428 if (not_array) btest = BoolTest(btest).negate();
4429 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4430 Node* ctrl = generate_fair_guard(bol, region);
4431 Node* is_array_ctrl = not_array ? control() : ctrl;
4432 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4433 // Keep track of the fact that 'obj' is an array to prevent
4434 // array specific accesses from floating above the guard.
4435 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4436 }
4437 return ctrl;
4438 }
4439
4440
4441 //-----------------------inline_native_newArray--------------------------
4442 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4443 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4444 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4445 Node* mirror;
4446 Node* count_val;
4447 if (uninitialized) {
4448 null_check_receiver();
4449 mirror = argument(1);
4450 count_val = argument(2);
4451 } else {
4452 mirror = argument(0);
4453 count_val = argument(1);
4454 }
4455
4456 mirror = null_check(mirror);
4457 // If mirror or obj is dead, only null-path is taken.
4458 if (stopped()) return true;
4459
4460 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4461 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4462 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4463 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4464 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4465
4466 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4467 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4468 result_reg, _slow_path);
4469 Node* normal_ctl = control();
4470 Node* no_array_ctl = result_reg->in(_slow_path);
4471
4472 // Generate code for the slow case. We make a call to newArray().
4473 set_control(no_array_ctl);
4474 if (!stopped()) {
4475 // Either the input type is void.class, or else the
4476 // array klass has not yet been cached. Either the
4477 // ensuing call will throw an exception, or else it
4478 // will cache the array klass for next time.
4479 PreserveJVMState pjvms(this);
4480 CallJavaNode* slow_call = nullptr;
4481 if (uninitialized) {
4482 // Generate optimized virtual call (holder class 'Unsafe' is final)
4483 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4484 } else {
4485 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4486 }
4487 Node* slow_result = set_results_for_java_call(slow_call);
4488 // this->control() comes from set_results_for_java_call
4489 result_reg->set_req(_slow_path, control());
4490 result_val->set_req(_slow_path, slow_result);
4491 result_io ->set_req(_slow_path, i_o());
4492 result_mem->set_req(_slow_path, reset_memory());
4493 }
4494
4495 set_control(normal_ctl);
4496 if (!stopped()) {
4497 // Normal case: The array type has been cached in the java.lang.Class.
4498 // The following call works fine even if the array type is polymorphic.
4499 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4500 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4501 result_reg->init_req(_normal_path, control());
4502 result_val->init_req(_normal_path, obj);
4503 result_io ->init_req(_normal_path, i_o());
4504 result_mem->init_req(_normal_path, reset_memory());
4505
4506 if (uninitialized) {
4507 // Mark the allocation so that zeroing is skipped
4508 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4509 alloc->maybe_set_complete(&_gvn);
4510 }
4511 }
4512
4513 // Return the combined state.
4514 set_i_o( _gvn.transform(result_io) );
4515 set_all_memory( _gvn.transform(result_mem));
4516
4517 C->set_has_split_ifs(true); // Has chance for split-if optimization
4518 set_result(result_reg, result_val);
4519 return true;
4520 }
4521
4522 //----------------------inline_native_getLength--------------------------
4523 // public static native int java.lang.reflect.Array.getLength(Object array);
4524 bool LibraryCallKit::inline_native_getLength() {
4525 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
4526
4527 Node* array = null_check(argument(0));
4528 // If array is dead, only null-path is taken.
4529 if (stopped()) return true;
4530
4531 // Deoptimize if it is a non-array.
4532 Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4533
4534 if (non_array != nullptr) {
4535 PreserveJVMState pjvms(this);
4536 set_control(non_array);
4537 uncommon_trap(Deoptimization::Reason_intrinsic,
4538 Deoptimization::Action_maybe_recompile);
4539 }
4540
4541 // If control is dead, only non-array-path is taken.
4542 if (stopped()) return true;
4543
4544 // The works fine even if the array type is polymorphic.
4545 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4546 Node* result = load_array_length(array);
4547
4548 C->set_has_split_ifs(true); // Has chance for split-if optimization
4549 set_result(result);
4550 return true;
4551 }
4552
4553 //------------------------inline_array_copyOf----------------------------
4554 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
4555 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
4556 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4557 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
4558
4559 // Get the arguments.
4560 Node* original = argument(0);
4561 Node* start = is_copyOfRange? argument(1): intcon(0);
4562 Node* end = is_copyOfRange? argument(2): argument(1);
4563 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4564
4565 Node* newcopy = nullptr;
4566
4567 // Set the original stack and the reexecute bit for the interpreter to reexecute
4568 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4569 { PreserveReexecuteState preexecs(this);
4570 jvms()->set_should_reexecute(true);
4571
4572 array_type_mirror = null_check(array_type_mirror);
4573 original = null_check(original);
4574
4575 // Check if a null path was taken unconditionally.
4576 if (stopped()) return true;
4577
4578 Node* orig_length = load_array_length(original);
4579
4580 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4581 klass_node = null_check(klass_node);
4582
4583 RegionNode* bailout = new RegionNode(1);
4584 record_for_igvn(bailout);
4585
4586 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4587 // Bail out if that is so.
4588 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4589 if (not_objArray != nullptr) {
4590 // Improve the klass node's type from the new optimistic assumption:
4591 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4592 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4593 Node* cast = new CastPPNode(control(), klass_node, akls);
4594 klass_node = _gvn.transform(cast);
4595 }
4596
4597 // Bail out if either start or end is negative.
4598 generate_negative_guard(start, bailout, &start);
4599 generate_negative_guard(end, bailout, &end);
4600
4601 Node* length = end;
4602 if (_gvn.type(start) != TypeInt::ZERO) {
4603 length = _gvn.transform(new SubINode(end, start));
4604 }
4605
4606 // Bail out if length is negative (i.e., if start > end).
4607 // Without this the new_array would throw
4608 // NegativeArraySizeException but IllegalArgumentException is what
4609 // should be thrown
4610 generate_negative_guard(length, bailout, &length);
4611
4612 // Bail out if start is larger than the original length
4613 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4614 generate_negative_guard(orig_tail, bailout, &orig_tail);
4615
4616 if (bailout->req() > 1) {
4617 PreserveJVMState pjvms(this);
4618 set_control(_gvn.transform(bailout));
4619 uncommon_trap(Deoptimization::Reason_intrinsic,
4620 Deoptimization::Action_maybe_recompile);
4621 }
4622
4623 if (!stopped()) {
4624 // How many elements will we copy from the original?
4625 // The answer is MinI(orig_tail, length).
4626 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4627
4628 // Generate a direct call to the right arraycopy function(s).
4629 // We know the copy is disjoint but we might not know if the
4630 // oop stores need checking.
4631 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4632 // This will fail a store-check if x contains any non-nulls.
4633
4634 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4635 // loads/stores but it is legal only if we're sure the
4636 // Arrays.copyOf would succeed. So we need all input arguments
4637 // to the copyOf to be validated, including that the copy to the
4638 // new array won't trigger an ArrayStoreException. That subtype
4639 // check can be optimized if we know something on the type of
4640 // the input array from type speculation.
4641 if (_gvn.type(klass_node)->singleton()) {
4642 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4643 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4644
4645 int test = C->static_subtype_check(superk, subk);
4646 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4647 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4648 if (t_original->speculative_type() != nullptr) {
4649 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4650 }
4651 }
4652 }
4653
4654 bool validated = false;
4655 // Reason_class_check rather than Reason_intrinsic because we
4656 // want to intrinsify even if this traps.
4657 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4658 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4659
4660 if (not_subtype_ctrl != top()) {
4661 PreserveJVMState pjvms(this);
4662 set_control(not_subtype_ctrl);
4663 uncommon_trap(Deoptimization::Reason_class_check,
4664 Deoptimization::Action_make_not_entrant);
4665 assert(stopped(), "Should be stopped");
4666 }
4667 validated = true;
4668 }
4669
4670 if (!stopped()) {
4671 newcopy = new_array(klass_node, length, 0); // no arguments to push
4672
4673 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4674 load_object_klass(original), klass_node);
4675 if (!is_copyOfRange) {
4676 ac->set_copyof(validated);
4677 } else {
4678 ac->set_copyofrange(validated);
4679 }
4680 Node* n = _gvn.transform(ac);
4681 if (n == ac) {
4682 ac->connect_outputs(this);
4683 } else {
4684 assert(validated, "shouldn't transform if all arguments not validated");
4685 set_all_memory(n);
4686 }
4687 }
4688 }
4689 } // original reexecute is set back here
4690
4691 C->set_has_split_ifs(true); // Has chance for split-if optimization
4692 if (!stopped()) {
4693 set_result(newcopy);
4694 }
4695 return true;
4696 }
4697
4698
4699 //----------------------generate_virtual_guard---------------------------
4700 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
4701 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4702 RegionNode* slow_region) {
4703 ciMethod* method = callee();
4704 int vtable_index = method->vtable_index();
4705 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4706 "bad index %d", vtable_index);
4707 // Get the Method* out of the appropriate vtable entry.
4708 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
4709 vtable_index*vtableEntry::size_in_bytes() +
4710 in_bytes(vtableEntry::method_offset());
4711 Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
4712 Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4713
4714 // Compare the target method with the expected method (e.g., Object.hashCode).
4715 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4716
4717 Node* native_call = makecon(native_call_addr);
4718 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
4719 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4720
4721 return generate_slow_guard(test_native, slow_region);
4722 }
4723
4724 //-----------------------generate_method_call----------------------------
4725 // Use generate_method_call to make a slow-call to the real
4726 // method if the fast path fails. An alternative would be to
4727 // use a stub like OptoRuntime::slow_arraycopy_Java.
4728 // This only works for expanding the current library call,
4729 // not another intrinsic. (E.g., don't use this for making an
4730 // arraycopy call inside of the copyOf intrinsic.)
4731 CallJavaNode*
4732 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4733 // When compiling the intrinsic method itself, do not use this technique.
4734 guarantee(callee() != C->method(), "cannot make slow-call to self");
4735
4736 ciMethod* method = callee();
4737 // ensure the JVMS we have will be correct for this call
4738 guarantee(method_id == method->intrinsic_id(), "must match");
4739
4740 const TypeFunc* tf = TypeFunc::make(method);
4741 if (res_not_null) {
4742 assert(tf->return_type() == T_OBJECT, "");
4743 const TypeTuple* range = tf->range();
4744 const Type** fields = TypeTuple::fields(range->cnt());
4745 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4746 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4747 tf = TypeFunc::make(tf->domain(), new_range);
4748 }
4749 CallJavaNode* slow_call;
4750 if (is_static) {
4751 assert(!is_virtual, "");
4752 slow_call = new CallStaticJavaNode(C, tf,
4753 SharedRuntime::get_resolve_static_call_stub(), method);
4754 } else if (is_virtual) {
4755 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4756 int vtable_index = Method::invalid_vtable_index;
4757 if (UseInlineCaches) {
4758 // Suppress the vtable call
4759 } else {
4760 // hashCode and clone are not a miranda methods,
4761 // so the vtable index is fixed.
4762 // No need to use the linkResolver to get it.
4763 vtable_index = method->vtable_index();
4764 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4765 "bad index %d", vtable_index);
4766 }
4767 slow_call = new CallDynamicJavaNode(tf,
4768 SharedRuntime::get_resolve_virtual_call_stub(),
4769 method, vtable_index);
4770 } else { // neither virtual nor static: opt_virtual
4771 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4772 slow_call = new CallStaticJavaNode(C, tf,
4773 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
4774 slow_call->set_optimized_virtual(true);
4775 }
4776 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
4777 // To be able to issue a direct call (optimized virtual or virtual)
4778 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
4779 // about the method being invoked should be attached to the call site to
4780 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
4781 slow_call->set_override_symbolic_info(true);
4782 }
4783 set_arguments_for_java_call(slow_call);
4784 set_edges_for_java_call(slow_call);
4785 return slow_call;
4786 }
4787
4788
4789 /**
4790 * Build special case code for calls to hashCode on an object. This call may
4791 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4792 * slightly different code.
4793 */
4794 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4795 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4796 assert(!(is_virtual && is_static), "either virtual, special, or static");
4797
4798 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4799
4800 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4801 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4802 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4803 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4804 Node* obj = nullptr;
4805 if (!is_static) {
4806 // Check for hashing null object
4807 obj = null_check_receiver();
4808 if (stopped()) return true; // unconditionally null
4809 result_reg->init_req(_null_path, top());
4810 result_val->init_req(_null_path, top());
4811 } else {
4812 // Do a null check, and return zero if null.
4813 // System.identityHashCode(null) == 0
4814 obj = argument(0);
4815 Node* null_ctl = top();
4816 obj = null_check_oop(obj, &null_ctl);
4817 result_reg->init_req(_null_path, null_ctl);
4818 result_val->init_req(_null_path, _gvn.intcon(0));
4819 }
4820
4821 // Unconditionally null? Then return right away.
4822 if (stopped()) {
4823 set_control( result_reg->in(_null_path));
4824 if (!stopped())
4825 set_result(result_val->in(_null_path));
4826 return true;
4827 }
4828
4829 // We only go to the fast case code if we pass a number of guards. The
4830 // paths which do not pass are accumulated in the slow_region.
4831 RegionNode* slow_region = new RegionNode(1);
4832 record_for_igvn(slow_region);
4833
4834 // If this is a virtual call, we generate a funny guard. We pull out
4835 // the vtable entry corresponding to hashCode() from the target object.
4836 // If the target method which we are calling happens to be the native
4837 // Object hashCode() method, we pass the guard. We do not need this
4838 // guard for non-virtual calls -- the caller is known to be the native
4839 // Object hashCode().
4840 if (is_virtual) {
4841 // After null check, get the object's klass.
4842 Node* obj_klass = load_object_klass(obj);
4843 generate_virtual_guard(obj_klass, slow_region);
4844 }
4845
4846 // Get the header out of the object, use LoadMarkNode when available
4847 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4848 // The control of the load must be null. Otherwise, the load can move before
4849 // the null check after castPP removal.
4850 Node* no_ctrl = nullptr;
4851 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4852
4853 if (!UseObjectMonitorTable) {
4854 // Test the header to see if it is safe to read w.r.t. locking.
4855 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4856 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4857 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4858 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4859 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4860
4861 generate_slow_guard(test_monitor, slow_region);
4862 }
4863
4864 // Get the hash value and check to see that it has been properly assigned.
4865 // We depend on hash_mask being at most 32 bits and avoid the use of
4866 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4867 // vm: see markWord.hpp.
4868 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4869 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4870 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4871 // This hack lets the hash bits live anywhere in the mark object now, as long
4872 // as the shift drops the relevant bits into the low 32 bits. Note that
4873 // Java spec says that HashCode is an int so there's no point in capturing
4874 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4875 hshifted_header = ConvX2I(hshifted_header);
4876 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4877
4878 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
4879 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4880 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4881
4882 generate_slow_guard(test_assigned, slow_region);
4883
4884 Node* init_mem = reset_memory();
4885 // fill in the rest of the null path:
4886 result_io ->init_req(_null_path, i_o());
4887 result_mem->init_req(_null_path, init_mem);
4888
4889 result_val->init_req(_fast_path, hash_val);
4890 result_reg->init_req(_fast_path, control());
4891 result_io ->init_req(_fast_path, i_o());
4892 result_mem->init_req(_fast_path, init_mem);
4893
4894 // Generate code for the slow case. We make a call to hashCode().
4895 set_control(_gvn.transform(slow_region));
4896 if (!stopped()) {
4897 // No need for PreserveJVMState, because we're using up the present state.
4898 set_all_memory(init_mem);
4899 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4900 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
4901 Node* slow_result = set_results_for_java_call(slow_call);
4902 // this->control() comes from set_results_for_java_call
4903 result_reg->init_req(_slow_path, control());
4904 result_val->init_req(_slow_path, slow_result);
4905 result_io ->set_req(_slow_path, i_o());
4906 result_mem ->set_req(_slow_path, reset_memory());
4907 }
4908
4909 // Return the combined state.
4910 set_i_o( _gvn.transform(result_io) );
4911 set_all_memory( _gvn.transform(result_mem));
4912
4913 set_result(result_reg, result_val);
4914 return true;
4915 }
4916
4917 //---------------------------inline_native_getClass----------------------------
4918 // public final native Class<?> java.lang.Object.getClass();
4919 //
4920 // Build special case code for calls to getClass on an object.
4921 bool LibraryCallKit::inline_native_getClass() {
4922 Node* obj = null_check_receiver();
4923 if (stopped()) return true;
4924 set_result(load_mirror_from_klass(load_object_klass(obj)));
4925 return true;
4926 }
4927
4928 //-----------------inline_native_Reflection_getCallerClass---------------------
4929 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4930 //
4931 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4932 //
4933 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4934 // in that it must skip particular security frames and checks for
4935 // caller sensitive methods.
4936 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4937 #ifndef PRODUCT
4938 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4939 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4940 }
4941 #endif
4942
4943 if (!jvms()->has_method()) {
4944 #ifndef PRODUCT
4945 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4946 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
4947 }
4948 #endif
4949 return false;
4950 }
4951
4952 // Walk back up the JVM state to find the caller at the required
4953 // depth.
4954 JVMState* caller_jvms = jvms();
4955
4956 // Cf. JVM_GetCallerClass
4957 // NOTE: Start the loop at depth 1 because the current JVM state does
4958 // not include the Reflection.getCallerClass() frame.
4959 for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
4960 ciMethod* m = caller_jvms->method();
4961 switch (n) {
4962 case 0:
4963 fatal("current JVM state does not include the Reflection.getCallerClass frame");
4964 break;
4965 case 1:
4966 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4967 if (!m->caller_sensitive()) {
4968 #ifndef PRODUCT
4969 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4970 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
4971 }
4972 #endif
4973 return false; // bail-out; let JVM_GetCallerClass do the work
4974 }
4975 break;
4976 default:
4977 if (!m->is_ignored_by_security_stack_walk()) {
4978 // We have reached the desired frame; return the holder class.
4979 // Acquire method holder as java.lang.Class and push as constant.
4980 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4981 ciInstance* caller_mirror = caller_klass->java_mirror();
4982 set_result(makecon(TypeInstPtr::make(caller_mirror)));
4983
4984 #ifndef PRODUCT
4985 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4986 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());
4987 tty->print_cr(" JVM state at this point:");
4988 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4989 ciMethod* m = jvms()->of_depth(i)->method();
4990 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4991 }
4992 }
4993 #endif
4994 return true;
4995 }
4996 break;
4997 }
4998 }
4999
5000 #ifndef PRODUCT
5001 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5002 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5003 tty->print_cr(" JVM state at this point:");
5004 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5005 ciMethod* m = jvms()->of_depth(i)->method();
5006 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5007 }
5008 }
5009 #endif
5010
5011 return false; // bail-out; let JVM_GetCallerClass do the work
5012 }
5013
5014 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5015 Node* arg = argument(0);
5016 Node* result = nullptr;
5017
5018 switch (id) {
5019 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
5020 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
5021 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
5022 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
5023 case vmIntrinsics::_floatToFloat16: result = new ConvF2HFNode(arg); break;
5024 case vmIntrinsics::_float16ToFloat: result = new ConvHF2FNode(arg); break;
5025
5026 case vmIntrinsics::_doubleToLongBits: {
5027 // two paths (plus control) merge in a wood
5028 RegionNode *r = new RegionNode(3);
5029 Node *phi = new PhiNode(r, TypeLong::LONG);
5030
5031 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5032 // Build the boolean node
5033 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5034
5035 // Branch either way.
5036 // NaN case is less traveled, which makes all the difference.
5037 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5038 Node *opt_isnan = _gvn.transform(ifisnan);
5039 assert( opt_isnan->is_If(), "Expect an IfNode");
5040 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5041 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5042
5043 set_control(iftrue);
5044
5045 static const jlong nan_bits = CONST64(0x7ff8000000000000);
5046 Node *slow_result = longcon(nan_bits); // return NaN
5047 phi->init_req(1, _gvn.transform( slow_result ));
5048 r->init_req(1, iftrue);
5049
5050 // Else fall through
5051 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5052 set_control(iffalse);
5053
5054 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5055 r->init_req(2, iffalse);
5056
5057 // Post merge
5058 set_control(_gvn.transform(r));
5059 record_for_igvn(r);
5060
5061 C->set_has_split_ifs(true); // Has chance for split-if optimization
5062 result = phi;
5063 assert(result->bottom_type()->isa_long(), "must be");
5064 break;
5065 }
5066
5067 case vmIntrinsics::_floatToIntBits: {
5068 // two paths (plus control) merge in a wood
5069 RegionNode *r = new RegionNode(3);
5070 Node *phi = new PhiNode(r, TypeInt::INT);
5071
5072 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5073 // Build the boolean node
5074 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5075
5076 // Branch either way.
5077 // NaN case is less traveled, which makes all the difference.
5078 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5079 Node *opt_isnan = _gvn.transform(ifisnan);
5080 assert( opt_isnan->is_If(), "Expect an IfNode");
5081 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5082 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5083
5084 set_control(iftrue);
5085
5086 static const jint nan_bits = 0x7fc00000;
5087 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5088 phi->init_req(1, _gvn.transform( slow_result ));
5089 r->init_req(1, iftrue);
5090
5091 // Else fall through
5092 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5093 set_control(iffalse);
5094
5095 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5096 r->init_req(2, iffalse);
5097
5098 // Post merge
5099 set_control(_gvn.transform(r));
5100 record_for_igvn(r);
5101
5102 C->set_has_split_ifs(true); // Has chance for split-if optimization
5103 result = phi;
5104 assert(result->bottom_type()->isa_int(), "must be");
5105 break;
5106 }
5107
5108 default:
5109 fatal_unexpected_iid(id);
5110 break;
5111 }
5112 set_result(_gvn.transform(result));
5113 return true;
5114 }
5115
5116 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5117 Node* arg = argument(0);
5118 Node* result = nullptr;
5119
5120 switch (id) {
5121 case vmIntrinsics::_floatIsInfinite:
5122 result = new IsInfiniteFNode(arg);
5123 break;
5124 case vmIntrinsics::_floatIsFinite:
5125 result = new IsFiniteFNode(arg);
5126 break;
5127 case vmIntrinsics::_doubleIsInfinite:
5128 result = new IsInfiniteDNode(arg);
5129 break;
5130 case vmIntrinsics::_doubleIsFinite:
5131 result = new IsFiniteDNode(arg);
5132 break;
5133 default:
5134 fatal_unexpected_iid(id);
5135 break;
5136 }
5137 set_result(_gvn.transform(result));
5138 return true;
5139 }
5140
5141 //----------------------inline_unsafe_copyMemory-------------------------
5142 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5143
5144 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5145 const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5146 const Type* base_t = gvn.type(base);
5147
5148 bool in_native = (base_t == TypePtr::NULL_PTR);
5149 bool in_heap = !TypePtr::NULL_PTR->higher_equal(base_t);
5150 bool is_mixed = !in_heap && !in_native;
5151
5152 if (is_mixed) {
5153 return true; // mixed accesses can touch both on-heap and off-heap memory
5154 }
5155 if (in_heap) {
5156 bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5157 if (!is_prim_array) {
5158 // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5159 // there's not enough type information available to determine proper memory slice for it.
5160 return true;
5161 }
5162 }
5163 return false;
5164 }
5165
5166 bool LibraryCallKit::inline_unsafe_copyMemory() {
5167 if (callee()->is_static()) return false; // caller must have the capability!
5168 null_check_receiver(); // null-check receiver
5169 if (stopped()) return true;
5170
5171 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5172
5173 Node* src_base = argument(1); // type: oop
5174 Node* src_off = ConvL2X(argument(2)); // type: long
5175 Node* dst_base = argument(4); // type: oop
5176 Node* dst_off = ConvL2X(argument(5)); // type: long
5177 Node* size = ConvL2X(argument(7)); // type: long
5178
5179 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5180 "fieldOffset must be byte-scaled");
5181
5182 Node* src_addr = make_unsafe_address(src_base, src_off);
5183 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5184
5185 Node* thread = _gvn.transform(new ThreadLocalNode());
5186 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5187 BasicType doing_unsafe_access_bt = T_BYTE;
5188 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5189
5190 // update volatile field
5191 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5192
5193 int flags = RC_LEAF | RC_NO_FP;
5194
5195 const TypePtr* dst_type = TypePtr::BOTTOM;
5196
5197 // Adjust memory effects of the runtime call based on input values.
5198 if (!has_wide_mem(_gvn, src_addr, src_base) &&
5199 !has_wide_mem(_gvn, dst_addr, dst_base)) {
5200 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5201
5202 const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5203 if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5204 flags |= RC_NARROW_MEM; // narrow in memory
5205 }
5206 }
5207
5208 // Call it. Note that the length argument is not scaled.
5209 make_runtime_call(flags,
5210 OptoRuntime::fast_arraycopy_Type(),
5211 StubRoutines::unsafe_arraycopy(),
5212 "unsafe_arraycopy",
5213 dst_type,
5214 src_addr, dst_addr, size XTOP);
5215
5216 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5217
5218 return true;
5219 }
5220
5221 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5222 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5223 bool LibraryCallKit::inline_unsafe_setMemory() {
5224 if (callee()->is_static()) return false; // caller must have the capability!
5225 null_check_receiver(); // null-check receiver
5226 if (stopped()) return true;
5227
5228 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5229
5230 Node* dst_base = argument(1); // type: oop
5231 Node* dst_off = ConvL2X(argument(2)); // type: long
5232 Node* size = ConvL2X(argument(4)); // type: long
5233 Node* byte = argument(6); // type: byte
5234
5235 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5236 "fieldOffset must be byte-scaled");
5237
5238 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5239
5240 Node* thread = _gvn.transform(new ThreadLocalNode());
5241 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5242 BasicType doing_unsafe_access_bt = T_BYTE;
5243 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5244
5245 // update volatile field
5246 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5247
5248 int flags = RC_LEAF | RC_NO_FP;
5249
5250 const TypePtr* dst_type = TypePtr::BOTTOM;
5251
5252 // Adjust memory effects of the runtime call based on input values.
5253 if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5254 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5255
5256 flags |= RC_NARROW_MEM; // narrow in memory
5257 }
5258
5259 // Call it. Note that the length argument is not scaled.
5260 make_runtime_call(flags,
5261 OptoRuntime::unsafe_setmemory_Type(),
5262 StubRoutines::unsafe_setmemory(),
5263 "unsafe_setmemory",
5264 dst_type,
5265 dst_addr, size XTOP, byte);
5266
5267 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5268
5269 return true;
5270 }
5271
5272 #undef XTOP
5273
5274 //------------------------clone_coping-----------------------------------
5275 // Helper function for inline_native_clone.
5276 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5277 assert(obj_size != nullptr, "");
5278 Node* raw_obj = alloc_obj->in(1);
5279 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5280
5281 AllocateNode* alloc = nullptr;
5282 if (ReduceBulkZeroing &&
5283 // If we are implementing an array clone without knowing its source type
5284 // (can happen when compiling the array-guarded branch of a reflective
5285 // Object.clone() invocation), initialize the array within the allocation.
5286 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5287 // to a runtime clone call that assumes fully initialized source arrays.
5288 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5289 // We will be completely responsible for initializing this object -
5290 // mark Initialize node as complete.
5291 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5292 // The object was just allocated - there should be no any stores!
5293 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5294 // Mark as complete_with_arraycopy so that on AllocateNode
5295 // expansion, we know this AllocateNode is initialized by an array
5296 // copy and a StoreStore barrier exists after the array copy.
5297 alloc->initialization()->set_complete_with_arraycopy();
5298 }
5299
5300 Node* size = _gvn.transform(obj_size);
5301 access_clone(obj, alloc_obj, size, is_array);
5302
5303 // Do not let reads from the cloned object float above the arraycopy.
5304 if (alloc != nullptr) {
5305 // Do not let stores that initialize this object be reordered with
5306 // a subsequent store that would make this object accessible by
5307 // other threads.
5308 // Record what AllocateNode this StoreStore protects so that
5309 // escape analysis can go from the MemBarStoreStoreNode to the
5310 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5311 // based on the escape status of the AllocateNode.
5312 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5313 } else {
5314 insert_mem_bar(Op_MemBarCPUOrder);
5315 }
5316 }
5317
5318 //------------------------inline_native_clone----------------------------
5319 // protected native Object java.lang.Object.clone();
5320 //
5321 // Here are the simple edge cases:
5322 // null receiver => normal trap
5323 // virtual and clone was overridden => slow path to out-of-line clone
5324 // not cloneable or finalizer => slow path to out-of-line Object.clone
5325 //
5326 // The general case has two steps, allocation and copying.
5327 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5328 //
5329 // Copying also has two cases, oop arrays and everything else.
5330 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5331 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5332 //
5333 // These steps fold up nicely if and when the cloned object's klass
5334 // can be sharply typed as an object array, a type array, or an instance.
5335 //
5336 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5337 PhiNode* result_val;
5338
5339 // Set the reexecute bit for the interpreter to reexecute
5340 // the bytecode that invokes Object.clone if deoptimization happens.
5341 { PreserveReexecuteState preexecs(this);
5342 jvms()->set_should_reexecute(true);
5343
5344 Node* obj = null_check_receiver();
5345 if (stopped()) return true;
5346
5347 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5348
5349 // If we are going to clone an instance, we need its exact type to
5350 // know the number and types of fields to convert the clone to
5351 // loads/stores. Maybe a speculative type can help us.
5352 if (!obj_type->klass_is_exact() &&
5353 obj_type->speculative_type() != nullptr &&
5354 obj_type->speculative_type()->is_instance_klass()) {
5355 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5356 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5357 !spec_ik->has_injected_fields()) {
5358 if (!obj_type->isa_instptr() ||
5359 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5360 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5361 }
5362 }
5363 }
5364
5365 // Conservatively insert a memory barrier on all memory slices.
5366 // Do not let writes into the original float below the clone.
5367 insert_mem_bar(Op_MemBarCPUOrder);
5368
5369 // paths into result_reg:
5370 enum {
5371 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5372 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5373 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5374 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5375 PATH_LIMIT
5376 };
5377 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5378 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5379 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5380 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5381 record_for_igvn(result_reg);
5382
5383 Node* obj_klass = load_object_klass(obj);
5384 Node* array_obj = obj;
5385 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5386 if (array_ctl != nullptr) {
5387 // It's an array.
5388 PreserveJVMState pjvms(this);
5389 set_control(array_ctl);
5390 Node* obj_length = load_array_length(array_obj);
5391 Node* array_size = nullptr; // Size of the array without object alignment padding.
5392 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5393
5394 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5395 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5396 // If it is an oop array, it requires very special treatment,
5397 // because gc barriers are required when accessing the array.
5398 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5399 if (is_obja != nullptr) {
5400 PreserveJVMState pjvms2(this);
5401 set_control(is_obja);
5402 // Generate a direct call to the right arraycopy function(s).
5403 // Clones are always tightly coupled.
5404 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5405 ac->set_clone_oop_array();
5406 Node* n = _gvn.transform(ac);
5407 assert(n == ac, "cannot disappear");
5408 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5409
5410 result_reg->init_req(_objArray_path, control());
5411 result_val->init_req(_objArray_path, alloc_obj);
5412 result_i_o ->set_req(_objArray_path, i_o());
5413 result_mem ->set_req(_objArray_path, reset_memory());
5414 }
5415 }
5416 // Otherwise, there are no barriers to worry about.
5417 // (We can dispense with card marks if we know the allocation
5418 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5419 // causes the non-eden paths to take compensating steps to
5420 // simulate a fresh allocation, so that no further
5421 // card marks are required in compiled code to initialize
5422 // the object.)
5423
5424 if (!stopped()) {
5425 copy_to_clone(array_obj, alloc_obj, array_size, true);
5426
5427 // Present the results of the copy.
5428 result_reg->init_req(_array_path, control());
5429 result_val->init_req(_array_path, alloc_obj);
5430 result_i_o ->set_req(_array_path, i_o());
5431 result_mem ->set_req(_array_path, reset_memory());
5432 }
5433 }
5434
5435 // We only go to the instance fast case code if we pass a number of guards.
5436 // The paths which do not pass are accumulated in the slow_region.
5437 RegionNode* slow_region = new RegionNode(1);
5438 record_for_igvn(slow_region);
5439 if (!stopped()) {
5440 // It's an instance (we did array above). Make the slow-path tests.
5441 // If this is a virtual call, we generate a funny guard. We grab
5442 // the vtable entry corresponding to clone() from the target object.
5443 // If the target method which we are calling happens to be the
5444 // Object clone() method, we pass the guard. We do not need this
5445 // guard for non-virtual calls; the caller is known to be the native
5446 // Object clone().
5447 if (is_virtual) {
5448 generate_virtual_guard(obj_klass, slow_region);
5449 }
5450
5451 // The object must be easily cloneable and must not have a finalizer.
5452 // Both of these conditions may be checked in a single test.
5453 // We could optimize the test further, but we don't care.
5454 generate_misc_flags_guard(obj_klass,
5455 // Test both conditions:
5456 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5457 // Must be cloneable but not finalizer:
5458 KlassFlags::_misc_is_cloneable_fast,
5459 slow_region);
5460 }
5461
5462 if (!stopped()) {
5463 // It's an instance, and it passed the slow-path tests.
5464 PreserveJVMState pjvms(this);
5465 Node* obj_size = nullptr; // Total object size, including object alignment padding.
5466 // Need to deoptimize on exception from allocation since Object.clone intrinsic
5467 // is reexecuted if deoptimization occurs and there could be problems when merging
5468 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5469 Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5470
5471 copy_to_clone(obj, alloc_obj, obj_size, false);
5472
5473 // Present the results of the slow call.
5474 result_reg->init_req(_instance_path, control());
5475 result_val->init_req(_instance_path, alloc_obj);
5476 result_i_o ->set_req(_instance_path, i_o());
5477 result_mem ->set_req(_instance_path, reset_memory());
5478 }
5479
5480 // Generate code for the slow case. We make a call to clone().
5481 set_control(_gvn.transform(slow_region));
5482 if (!stopped()) {
5483 PreserveJVMState pjvms(this);
5484 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5485 // We need to deoptimize on exception (see comment above)
5486 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5487 // this->control() comes from set_results_for_java_call
5488 result_reg->init_req(_slow_path, control());
5489 result_val->init_req(_slow_path, slow_result);
5490 result_i_o ->set_req(_slow_path, i_o());
5491 result_mem ->set_req(_slow_path, reset_memory());
5492 }
5493
5494 // Return the combined state.
5495 set_control( _gvn.transform(result_reg));
5496 set_i_o( _gvn.transform(result_i_o));
5497 set_all_memory( _gvn.transform(result_mem));
5498 } // original reexecute is set back here
5499
5500 set_result(_gvn.transform(result_val));
5501 return true;
5502 }
5503
5504 // If we have a tightly coupled allocation, the arraycopy may take care
5505 // of the array initialization. If one of the guards we insert between
5506 // the allocation and the arraycopy causes a deoptimization, an
5507 // uninitialized array will escape the compiled method. To prevent that
5508 // we set the JVM state for uncommon traps between the allocation and
5509 // the arraycopy to the state before the allocation so, in case of
5510 // deoptimization, we'll reexecute the allocation and the
5511 // initialization.
5512 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
5513 if (alloc != nullptr) {
5514 ciMethod* trap_method = alloc->jvms()->method();
5515 int trap_bci = alloc->jvms()->bci();
5516
5517 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5518 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
5519 // Make sure there's no store between the allocation and the
5520 // arraycopy otherwise visible side effects could be rexecuted
5521 // in case of deoptimization and cause incorrect execution.
5522 bool no_interfering_store = true;
5523 Node* mem = alloc->in(TypeFunc::Memory);
5524 if (mem->is_MergeMem()) {
5525 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
5526 Node* n = mms.memory();
5527 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5528 assert(n->is_Store(), "what else?");
5529 no_interfering_store = false;
5530 break;
5531 }
5532 }
5533 } else {
5534 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
5535 Node* n = mms.memory();
5536 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5537 assert(n->is_Store(), "what else?");
5538 no_interfering_store = false;
5539 break;
5540 }
5541 }
5542 }
5543
5544 if (no_interfering_store) {
5545 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5546
5547 JVMState* saved_jvms = jvms();
5548 saved_reexecute_sp = _reexecute_sp;
5549
5550 set_jvms(sfpt->jvms());
5551 _reexecute_sp = jvms()->sp();
5552
5553 return saved_jvms;
5554 }
5555 }
5556 }
5557 return nullptr;
5558 }
5559
5560 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5561 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5562 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5563 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5564 uint size = alloc->req();
5565 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5566 old_jvms->set_map(sfpt);
5567 for (uint i = 0; i < size; i++) {
5568 sfpt->init_req(i, alloc->in(i));
5569 }
5570 // re-push array length for deoptimization
5571 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5572 old_jvms->set_sp(old_jvms->sp()+1);
5573 old_jvms->set_monoff(old_jvms->monoff()+1);
5574 old_jvms->set_scloff(old_jvms->scloff()+1);
5575 old_jvms->set_endoff(old_jvms->endoff()+1);
5576 old_jvms->set_should_reexecute(true);
5577
5578 sfpt->set_i_o(map()->i_o());
5579 sfpt->set_memory(map()->memory());
5580 sfpt->set_control(map()->control());
5581 return sfpt;
5582 }
5583
5584 // In case of a deoptimization, we restart execution at the
5585 // allocation, allocating a new array. We would leave an uninitialized
5586 // array in the heap that GCs wouldn't expect. Move the allocation
5587 // after the traps so we don't allocate the array if we
5588 // deoptimize. This is possible because tightly_coupled_allocation()
5589 // guarantees there's no observer of the allocated array at this point
5590 // and the control flow is simple enough.
5591 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5592 int saved_reexecute_sp, uint new_idx) {
5593 if (saved_jvms_before_guards != nullptr && !stopped()) {
5594 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5595
5596 assert(alloc != nullptr, "only with a tightly coupled allocation");
5597 // restore JVM state to the state at the arraycopy
5598 saved_jvms_before_guards->map()->set_control(map()->control());
5599 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5600 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5601 // If we've improved the types of some nodes (null check) while
5602 // emitting the guards, propagate them to the current state
5603 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5604 set_jvms(saved_jvms_before_guards);
5605 _reexecute_sp = saved_reexecute_sp;
5606
5607 // Remove the allocation from above the guards
5608 CallProjections callprojs;
5609 alloc->extract_projections(&callprojs, true);
5610 InitializeNode* init = alloc->initialization();
5611 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5612 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5613 init->replace_mem_projs_by(alloc_mem, C);
5614
5615 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5616 // the allocation (i.e. is only valid if the allocation succeeds):
5617 // 1) replace CastIINode with AllocateArrayNode's length here
5618 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5619 //
5620 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5621 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5622 Node* init_control = init->proj_out(TypeFunc::Control);
5623 Node* alloc_length = alloc->Ideal_length();
5624 #ifdef ASSERT
5625 Node* prev_cast = nullptr;
5626 #endif
5627 for (uint i = 0; i < init_control->outcnt(); i++) {
5628 Node* init_out = init_control->raw_out(i);
5629 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5630 #ifdef ASSERT
5631 if (prev_cast == nullptr) {
5632 prev_cast = init_out;
5633 } else {
5634 if (prev_cast->cmp(*init_out) == false) {
5635 prev_cast->dump();
5636 init_out->dump();
5637 assert(false, "not equal CastIINode");
5638 }
5639 }
5640 #endif
5641 C->gvn_replace_by(init_out, alloc_length);
5642 }
5643 }
5644 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5645
5646 // move the allocation here (after the guards)
5647 _gvn.hash_delete(alloc);
5648 alloc->set_req(TypeFunc::Control, control());
5649 alloc->set_req(TypeFunc::I_O, i_o());
5650 Node *mem = reset_memory();
5651 set_all_memory(mem);
5652 alloc->set_req(TypeFunc::Memory, mem);
5653 set_control(init->proj_out_or_null(TypeFunc::Control));
5654 set_i_o(callprojs.fallthrough_ioproj);
5655
5656 // Update memory as done in GraphKit::set_output_for_allocation()
5657 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5658 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5659 if (ary_type->isa_aryptr() && length_type != nullptr) {
5660 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5661 }
5662 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5663 int elemidx = C->get_alias_index(telemref);
5664 // Need to properly move every memory projection for the Initialize
5665 #ifdef ASSERT
5666 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5667 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5668 #endif
5669 auto move_proj = [&](ProjNode* proj) {
5670 int alias_idx = C->get_alias_index(proj->adr_type());
5671 assert(alias_idx == Compile::AliasIdxRaw ||
5672 alias_idx == elemidx ||
5673 alias_idx == mark_idx ||
5674 alias_idx == klass_idx, "should be raw memory or array element type");
5675 set_memory(proj, alias_idx);
5676 };
5677 init->for_each_proj(move_proj, TypeFunc::Memory);
5678
5679 Node* allocx = _gvn.transform(alloc);
5680 assert(allocx == alloc, "where has the allocation gone?");
5681 assert(dest->is_CheckCastPP(), "not an allocation result?");
5682
5683 _gvn.hash_delete(dest);
5684 dest->set_req(0, control());
5685 Node* destx = _gvn.transform(dest);
5686 assert(destx == dest, "where has the allocation result gone?");
5687
5688 array_ideal_length(alloc, ary_type, true);
5689 }
5690 }
5691
5692 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
5693 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
5694 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
5695 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
5696 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
5697 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
5698 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
5699 JVMState* saved_jvms_before_guards) {
5700 if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
5701 // There is at least one unrelated uncommon trap which needs to be replaced.
5702 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5703
5704 JVMState* saved_jvms = jvms();
5705 const int saved_reexecute_sp = _reexecute_sp;
5706 set_jvms(sfpt->jvms());
5707 _reexecute_sp = jvms()->sp();
5708
5709 replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
5710
5711 // Restore state
5712 set_jvms(saved_jvms);
5713 _reexecute_sp = saved_reexecute_sp;
5714 }
5715 }
5716
5717 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
5718 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
5719 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
5720 Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
5721 while (if_proj->is_IfProj()) {
5722 CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
5723 if (uncommon_trap != nullptr) {
5724 create_new_uncommon_trap(uncommon_trap);
5725 }
5726 assert(if_proj->in(0)->is_If(), "must be If");
5727 if_proj = if_proj->in(0)->in(0);
5728 }
5729 assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
5730 "must have reached control projection of init node");
5731 }
5732
5733 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
5734 const int trap_request = uncommon_trap_call->uncommon_trap_request();
5735 assert(trap_request != 0, "no valid UCT trap request");
5736 PreserveJVMState pjvms(this);
5737 set_control(uncommon_trap_call->in(0));
5738 uncommon_trap(Deoptimization::trap_request_reason(trap_request),
5739 Deoptimization::trap_request_action(trap_request));
5740 assert(stopped(), "Should be stopped");
5741 _gvn.hash_delete(uncommon_trap_call);
5742 uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
5743 }
5744
5745 // Common checks for array sorting intrinsics arguments.
5746 // Returns `true` if checks passed.
5747 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
5748 // check address of the class
5749 if (elementType == nullptr || elementType->is_top()) {
5750 return false; // dead path
5751 }
5752 const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
5753 if (elem_klass == nullptr) {
5754 return false; // dead path
5755 }
5756 // java_mirror_type() returns non-null for compile-time Class constants only
5757 ciType* elem_type = elem_klass->java_mirror_type();
5758 if (elem_type == nullptr) {
5759 return false;
5760 }
5761 bt = elem_type->basic_type();
5762 // Disable the intrinsic if the CPU does not support SIMD sort
5763 if (!Matcher::supports_simd_sort(bt)) {
5764 return false;
5765 }
5766 // check address of the array
5767 if (obj == nullptr || obj->is_top()) {
5768 return false; // dead path
5769 }
5770 const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
5771 if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
5772 return false; // failed input validation
5773 }
5774 return true;
5775 }
5776
5777 //------------------------------inline_array_partition-----------------------
5778 bool LibraryCallKit::inline_array_partition() {
5779 address stubAddr = StubRoutines::select_array_partition_function();
5780 if (stubAddr == nullptr) {
5781 return false; // Intrinsic's stub is not implemented on this platform
5782 }
5783 assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
5784
5785 // no receiver because it is a static method
5786 Node* elementType = argument(0);
5787 Node* obj = argument(1);
5788 Node* offset = argument(2); // long
5789 Node* fromIndex = argument(4);
5790 Node* toIndex = argument(5);
5791 Node* indexPivot1 = argument(6);
5792 Node* indexPivot2 = argument(7);
5793 // PartitionOperation: argument(8) is ignored
5794
5795 Node* pivotIndices = nullptr;
5796 BasicType bt = T_ILLEGAL;
5797
5798 if (!check_array_sort_arguments(elementType, obj, bt)) {
5799 return false;
5800 }
5801 null_check(obj);
5802 // If obj is dead, only null-path is taken.
5803 if (stopped()) {
5804 return true;
5805 }
5806 // Set the original stack and the reexecute bit for the interpreter to reexecute
5807 // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
5808 { PreserveReexecuteState preexecs(this);
5809 jvms()->set_should_reexecute(true);
5810
5811 Node* obj_adr = make_unsafe_address(obj, offset);
5812
5813 // create the pivotIndices array of type int and size = 2
5814 Node* size = intcon(2);
5815 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
5816 pivotIndices = new_array(klass_node, size, 0); // no arguments to push
5817 AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
5818 guarantee(alloc != nullptr, "created above");
5819 Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
5820
5821 // pass the basic type enum to the stub
5822 Node* elemType = intcon(bt);
5823
5824 // Call the stub
5825 const char *stubName = "array_partition_stub";
5826 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
5827 stubAddr, stubName, TypePtr::BOTTOM,
5828 obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
5829 indexPivot1, indexPivot2);
5830
5831 } // original reexecute is set back here
5832
5833 if (!stopped()) {
5834 set_result(pivotIndices);
5835 }
5836
5837 return true;
5838 }
5839
5840
5841 //------------------------------inline_array_sort-----------------------
5842 bool LibraryCallKit::inline_array_sort() {
5843 address stubAddr = StubRoutines::select_arraysort_function();
5844 if (stubAddr == nullptr) {
5845 return false; // Intrinsic's stub is not implemented on this platform
5846 }
5847 assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
5848
5849 // no receiver because it is a static method
5850 Node* elementType = argument(0);
5851 Node* obj = argument(1);
5852 Node* offset = argument(2); // long
5853 Node* fromIndex = argument(4);
5854 Node* toIndex = argument(5);
5855 // SortOperation: argument(6) is ignored
5856
5857 BasicType bt = T_ILLEGAL;
5858
5859 if (!check_array_sort_arguments(elementType, obj, bt)) {
5860 return false;
5861 }
5862 null_check(obj);
5863 // If obj is dead, only null-path is taken.
5864 if (stopped()) {
5865 return true;
5866 }
5867 Node* obj_adr = make_unsafe_address(obj, offset);
5868
5869 // pass the basic type enum to the stub
5870 Node* elemType = intcon(bt);
5871
5872 // Call the stub.
5873 const char *stubName = "arraysort_stub";
5874 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
5875 stubAddr, stubName, TypePtr::BOTTOM,
5876 obj_adr, elemType, fromIndex, toIndex);
5877
5878 return true;
5879 }
5880
5881
5882 //------------------------------inline_arraycopy-----------------------
5883 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
5884 // Object dest, int destPos,
5885 // int length);
5886 bool LibraryCallKit::inline_arraycopy() {
5887 // Get the arguments.
5888 Node* src = argument(0); // type: oop
5889 Node* src_offset = argument(1); // type: int
5890 Node* dest = argument(2); // type: oop
5891 Node* dest_offset = argument(3); // type: int
5892 Node* length = argument(4); // type: int
5893
5894 uint new_idx = C->unique();
5895
5896 // Check for allocation before we add nodes that would confuse
5897 // tightly_coupled_allocation()
5898 AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
5899
5900 int saved_reexecute_sp = -1;
5901 JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
5902 // See arraycopy_restore_alloc_state() comment
5903 // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
5904 // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
5905 // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
5906 bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
5907
5908 // The following tests must be performed
5909 // (1) src and dest are arrays.
5910 // (2) src and dest arrays must have elements of the same BasicType
5911 // (3) src and dest must not be null.
5912 // (4) src_offset must not be negative.
5913 // (5) dest_offset must not be negative.
5914 // (6) length must not be negative.
5915 // (7) src_offset + length must not exceed length of src.
5916 // (8) dest_offset + length must not exceed length of dest.
5917 // (9) each element of an oop array must be assignable
5918
5919 // (3) src and dest must not be null.
5920 // always do this here because we need the JVM state for uncommon traps
5921 Node* null_ctl = top();
5922 src = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
5923 assert(null_ctl->is_top(), "no null control here");
5924 dest = null_check(dest, T_ARRAY);
5925
5926 if (!can_emit_guards) {
5927 // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
5928 // guards but the arraycopy node could still take advantage of a
5929 // tightly allocated allocation. tightly_coupled_allocation() is
5930 // called again to make sure it takes the null check above into
5931 // account: the null check is mandatory and if it caused an
5932 // uncommon trap to be emitted then the allocation can't be
5933 // considered tightly coupled in this context.
5934 alloc = tightly_coupled_allocation(dest);
5935 }
5936
5937 bool validated = false;
5938
5939 const Type* src_type = _gvn.type(src);
5940 const Type* dest_type = _gvn.type(dest);
5941 const TypeAryPtr* top_src = src_type->isa_aryptr();
5942 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5943
5944 // Do we have the type of src?
5945 bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5946 // Do we have the type of dest?
5947 bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5948 // Is the type for src from speculation?
5949 bool src_spec = false;
5950 // Is the type for dest from speculation?
5951 bool dest_spec = false;
5952
5953 if ((!has_src || !has_dest) && can_emit_guards) {
5954 // We don't have sufficient type information, let's see if
5955 // speculative types can help. We need to have types for both src
5956 // and dest so that it pays off.
5957
5958 // Do we already have or could we have type information for src
5959 bool could_have_src = has_src;
5960 // Do we already have or could we have type information for dest
5961 bool could_have_dest = has_dest;
5962
5963 ciKlass* src_k = nullptr;
5964 if (!has_src) {
5965 src_k = src_type->speculative_type_not_null();
5966 if (src_k != nullptr && src_k->is_array_klass()) {
5967 could_have_src = true;
5968 }
5969 }
5970
5971 ciKlass* dest_k = nullptr;
5972 if (!has_dest) {
5973 dest_k = dest_type->speculative_type_not_null();
5974 if (dest_k != nullptr && dest_k->is_array_klass()) {
5975 could_have_dest = true;
5976 }
5977 }
5978
5979 if (could_have_src && could_have_dest) {
5980 // This is going to pay off so emit the required guards
5981 if (!has_src) {
5982 src = maybe_cast_profiled_obj(src, src_k, true);
5983 src_type = _gvn.type(src);
5984 top_src = src_type->isa_aryptr();
5985 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5986 src_spec = true;
5987 }
5988 if (!has_dest) {
5989 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5990 dest_type = _gvn.type(dest);
5991 top_dest = dest_type->isa_aryptr();
5992 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5993 dest_spec = true;
5994 }
5995 }
5996 }
5997
5998 if (has_src && has_dest && can_emit_guards) {
5999 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6000 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6001 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6002 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6003
6004 if (src_elem == dest_elem && src_elem == T_OBJECT) {
6005 // If both arrays are object arrays then having the exact types
6006 // for both will remove the need for a subtype check at runtime
6007 // before the call and may make it possible to pick a faster copy
6008 // routine (without a subtype check on every element)
6009 // Do we have the exact type of src?
6010 bool could_have_src = src_spec;
6011 // Do we have the exact type of dest?
6012 bool could_have_dest = dest_spec;
6013 ciKlass* src_k = nullptr;
6014 ciKlass* dest_k = nullptr;
6015 if (!src_spec) {
6016 src_k = src_type->speculative_type_not_null();
6017 if (src_k != nullptr && src_k->is_array_klass()) {
6018 could_have_src = true;
6019 }
6020 }
6021 if (!dest_spec) {
6022 dest_k = dest_type->speculative_type_not_null();
6023 if (dest_k != nullptr && dest_k->is_array_klass()) {
6024 could_have_dest = true;
6025 }
6026 }
6027 if (could_have_src && could_have_dest) {
6028 // If we can have both exact types, emit the missing guards
6029 if (could_have_src && !src_spec) {
6030 src = maybe_cast_profiled_obj(src, src_k, true);
6031 }
6032 if (could_have_dest && !dest_spec) {
6033 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6034 }
6035 }
6036 }
6037 }
6038
6039 ciMethod* trap_method = method();
6040 int trap_bci = bci();
6041 if (saved_jvms_before_guards != nullptr) {
6042 trap_method = alloc->jvms()->method();
6043 trap_bci = alloc->jvms()->bci();
6044 }
6045
6046 bool negative_length_guard_generated = false;
6047
6048 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6049 can_emit_guards &&
6050 !src->is_top() && !dest->is_top()) {
6051 // validate arguments: enables transformation the ArrayCopyNode
6052 validated = true;
6053
6054 RegionNode* slow_region = new RegionNode(1);
6055 record_for_igvn(slow_region);
6056
6057 // (1) src and dest are arrays.
6058 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6059 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6060
6061 // (2) src and dest arrays must have elements of the same BasicType
6062 // done at macro expansion or at Ideal transformation time
6063
6064 // (4) src_offset must not be negative.
6065 generate_negative_guard(src_offset, slow_region);
6066
6067 // (5) dest_offset must not be negative.
6068 generate_negative_guard(dest_offset, slow_region);
6069
6070 // (7) src_offset + length must not exceed length of src.
6071 generate_limit_guard(src_offset, length,
6072 load_array_length(src),
6073 slow_region);
6074
6075 // (8) dest_offset + length must not exceed length of dest.
6076 generate_limit_guard(dest_offset, length,
6077 load_array_length(dest),
6078 slow_region);
6079
6080 // (6) length must not be negative.
6081 // This is also checked in generate_arraycopy() during macro expansion, but
6082 // we also have to check it here for the case where the ArrayCopyNode will
6083 // be eliminated by Escape Analysis.
6084 if (EliminateAllocations) {
6085 generate_negative_guard(length, slow_region);
6086 negative_length_guard_generated = true;
6087 }
6088
6089 // (9) each element of an oop array must be assignable
6090 Node* dest_klass = load_object_klass(dest);
6091 if (src != dest) {
6092 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6093
6094 if (not_subtype_ctrl != top()) {
6095 PreserveJVMState pjvms(this);
6096 set_control(not_subtype_ctrl);
6097 uncommon_trap(Deoptimization::Reason_intrinsic,
6098 Deoptimization::Action_make_not_entrant);
6099 assert(stopped(), "Should be stopped");
6100 }
6101 }
6102 {
6103 PreserveJVMState pjvms(this);
6104 set_control(_gvn.transform(slow_region));
6105 uncommon_trap(Deoptimization::Reason_intrinsic,
6106 Deoptimization::Action_make_not_entrant);
6107 assert(stopped(), "Should be stopped");
6108 }
6109
6110 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6111 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6112 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6113 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6114 }
6115
6116 if (stopped()) {
6117 return true;
6118 }
6119
6120 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6121 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6122 // so the compiler has a chance to eliminate them: during macro expansion,
6123 // we have to set their control (CastPP nodes are eliminated).
6124 load_object_klass(src), load_object_klass(dest),
6125 load_array_length(src), load_array_length(dest));
6126
6127 ac->set_arraycopy(validated);
6128
6129 Node* n = _gvn.transform(ac);
6130 if (n == ac) {
6131 ac->connect_outputs(this);
6132 } else {
6133 assert(validated, "shouldn't transform if all arguments not validated");
6134 set_all_memory(n);
6135 }
6136 clear_upper_avx();
6137
6138
6139 return true;
6140 }
6141
6142
6143 // Helper function which determines if an arraycopy immediately follows
6144 // an allocation, with no intervening tests or other escapes for the object.
6145 AllocateArrayNode*
6146 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6147 if (stopped()) return nullptr; // no fast path
6148 if (!C->do_aliasing()) return nullptr; // no MergeMems around
6149
6150 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6151 if (alloc == nullptr) return nullptr;
6152
6153 Node* rawmem = memory(Compile::AliasIdxRaw);
6154 // Is the allocation's memory state untouched?
6155 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6156 // Bail out if there have been raw-memory effects since the allocation.
6157 // (Example: There might have been a call or safepoint.)
6158 return nullptr;
6159 }
6160 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6161 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6162 return nullptr;
6163 }
6164
6165 // There must be no unexpected observers of this allocation.
6166 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6167 Node* obs = ptr->fast_out(i);
6168 if (obs != this->map()) {
6169 return nullptr;
6170 }
6171 }
6172
6173 // This arraycopy must unconditionally follow the allocation of the ptr.
6174 Node* alloc_ctl = ptr->in(0);
6175 Node* ctl = control();
6176 while (ctl != alloc_ctl) {
6177 // There may be guards which feed into the slow_region.
6178 // Any other control flow means that we might not get a chance
6179 // to finish initializing the allocated object.
6180 // Various low-level checks bottom out in uncommon traps. These
6181 // are considered safe since we've already checked above that
6182 // there is no unexpected observer of this allocation.
6183 if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6184 assert(ctl->in(0)->is_If(), "must be If");
6185 ctl = ctl->in(0)->in(0);
6186 } else {
6187 return nullptr;
6188 }
6189 }
6190
6191 // If we get this far, we have an allocation which immediately
6192 // precedes the arraycopy, and we can take over zeroing the new object.
6193 // The arraycopy will finish the initialization, and provide
6194 // a new control state to which we will anchor the destination pointer.
6195
6196 return alloc;
6197 }
6198
6199 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6200 if (node->is_IfProj()) {
6201 IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6202 for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6203 Node* obs = other_proj->fast_out(j);
6204 if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6205 (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6206 return obs->as_CallStaticJava();
6207 }
6208 }
6209 }
6210 return nullptr;
6211 }
6212
6213 //-------------inline_encodeISOArray-----------------------------------
6214 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6215 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6216 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6217 // encode char[] to byte[] in ISO_8859_1 or ASCII
6218 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6219 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6220 // no receiver since it is static method
6221 Node *src = argument(0);
6222 Node *src_offset = argument(1);
6223 Node *dst = argument(2);
6224 Node *dst_offset = argument(3);
6225 Node *length = argument(4);
6226
6227 // Cast source & target arrays to not-null
6228 src = must_be_not_null(src, true);
6229 dst = must_be_not_null(dst, true);
6230 if (stopped()) {
6231 return true;
6232 }
6233
6234 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6235 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6236 if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6237 dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6238 // failed array check
6239 return false;
6240 }
6241
6242 // Figure out the size and type of the elements we will be copying.
6243 BasicType src_elem = src_type->elem()->array_element_basic_type();
6244 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6245 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6246 return false;
6247 }
6248
6249 // Check source & target bounds
6250 RegionNode* bailout = create_bailout();
6251 generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6252 generate_string_range_check(dst, dst_offset, length, false, bailout);
6253 if (check_bailout(bailout)) {
6254 return true;
6255 }
6256
6257 Node* src_start = array_element_address(src, src_offset, T_CHAR);
6258 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6259 // 'src_start' points to src array + scaled offset
6260 // 'dst_start' points to dst array + scaled offset
6261
6262 // See GraphKit::compress_string
6263 const TypePtr* adr_type;
6264 Node* mem = capture_memory(adr_type, src_type, dst_type);
6265 Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
6266 enc = _gvn.transform(enc);
6267 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6268 memory_effect(res_mem, src_type, dst_type);
6269
6270 set_result(enc);
6271 clear_upper_avx();
6272
6273 return true;
6274 }
6275
6276 //-------------inline_multiplyToLen-----------------------------------
6277 bool LibraryCallKit::inline_multiplyToLen() {
6278 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6279
6280 address stubAddr = StubRoutines::multiplyToLen();
6281 if (stubAddr == nullptr) {
6282 return false; // Intrinsic's stub is not implemented on this platform
6283 }
6284 const char* stubName = "multiplyToLen";
6285
6286 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6287
6288 // no receiver because it is a static method
6289 Node* x = argument(0);
6290 Node* xlen = argument(1);
6291 Node* y = argument(2);
6292 Node* ylen = argument(3);
6293 Node* z = argument(4);
6294
6295 x = must_be_not_null(x, true);
6296 y = must_be_not_null(y, true);
6297
6298 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6299 const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6300 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6301 y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6302 // failed array check
6303 return false;
6304 }
6305
6306 BasicType x_elem = x_type->elem()->array_element_basic_type();
6307 BasicType y_elem = y_type->elem()->array_element_basic_type();
6308 if (x_elem != T_INT || y_elem != T_INT) {
6309 return false;
6310 }
6311
6312 Node* x_start = array_element_address(x, intcon(0), x_elem);
6313 Node* y_start = array_element_address(y, intcon(0), y_elem);
6314 // 'x_start' points to x array + scaled xlen
6315 // 'y_start' points to y array + scaled ylen
6316
6317 Node* z_start = array_element_address(z, intcon(0), T_INT);
6318
6319 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6320 OptoRuntime::multiplyToLen_Type(),
6321 stubAddr, stubName, TypePtr::BOTTOM,
6322 x_start, xlen, y_start, ylen, z_start);
6323
6324 C->set_has_split_ifs(true); // Has chance for split-if optimization
6325 set_result(z);
6326 return true;
6327 }
6328
6329 //-------------inline_squareToLen------------------------------------
6330 bool LibraryCallKit::inline_squareToLen() {
6331 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6332
6333 address stubAddr = StubRoutines::squareToLen();
6334 if (stubAddr == nullptr) {
6335 return false; // Intrinsic's stub is not implemented on this platform
6336 }
6337 const char* stubName = "squareToLen";
6338
6339 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6340
6341 Node* x = argument(0);
6342 Node* len = argument(1);
6343 Node* z = argument(2);
6344 Node* zlen = argument(3);
6345
6346 x = must_be_not_null(x, true);
6347 z = must_be_not_null(z, true);
6348
6349 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6350 const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6351 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6352 z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6353 // failed array check
6354 return false;
6355 }
6356
6357 BasicType x_elem = x_type->elem()->array_element_basic_type();
6358 BasicType z_elem = z_type->elem()->array_element_basic_type();
6359 if (x_elem != T_INT || z_elem != T_INT) {
6360 return false;
6361 }
6362
6363
6364 Node* x_start = array_element_address(x, intcon(0), x_elem);
6365 Node* z_start = array_element_address(z, intcon(0), z_elem);
6366
6367 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6368 OptoRuntime::squareToLen_Type(),
6369 stubAddr, stubName, TypePtr::BOTTOM,
6370 x_start, len, z_start, zlen);
6371
6372 set_result(z);
6373 return true;
6374 }
6375
6376 //-------------inline_mulAdd------------------------------------------
6377 bool LibraryCallKit::inline_mulAdd() {
6378 assert(UseMulAddIntrinsic, "not implemented on this platform");
6379
6380 address stubAddr = StubRoutines::mulAdd();
6381 if (stubAddr == nullptr) {
6382 return false; // Intrinsic's stub is not implemented on this platform
6383 }
6384 const char* stubName = "mulAdd";
6385
6386 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6387
6388 Node* out = argument(0);
6389 Node* in = argument(1);
6390 Node* offset = argument(2);
6391 Node* len = argument(3);
6392 Node* k = argument(4);
6393
6394 in = must_be_not_null(in, true);
6395 out = must_be_not_null(out, true);
6396
6397 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6398 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6399 if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6400 in_type == nullptr || in_type->elem() == Type::BOTTOM) {
6401 // failed array check
6402 return false;
6403 }
6404
6405 BasicType out_elem = out_type->elem()->array_element_basic_type();
6406 BasicType in_elem = in_type->elem()->array_element_basic_type();
6407 if (out_elem != T_INT || in_elem != T_INT) {
6408 return false;
6409 }
6410
6411 Node* outlen = load_array_length(out);
6412 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6413 Node* out_start = array_element_address(out, intcon(0), out_elem);
6414 Node* in_start = array_element_address(in, intcon(0), in_elem);
6415
6416 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6417 OptoRuntime::mulAdd_Type(),
6418 stubAddr, stubName, TypePtr::BOTTOM,
6419 out_start,in_start, new_offset, len, k);
6420 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6421 set_result(result);
6422 return true;
6423 }
6424
6425 //-------------inline_montgomeryMultiply-----------------------------------
6426 bool LibraryCallKit::inline_montgomeryMultiply() {
6427 address stubAddr = StubRoutines::montgomeryMultiply();
6428 if (stubAddr == nullptr) {
6429 return false; // Intrinsic's stub is not implemented on this platform
6430 }
6431
6432 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6433 const char* stubName = "montgomery_multiply";
6434
6435 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6436
6437 Node* a = argument(0);
6438 Node* b = argument(1);
6439 Node* n = argument(2);
6440 Node* len = argument(3);
6441 Node* inv = argument(4);
6442 Node* m = argument(6);
6443
6444 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6445 const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6446 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6447 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6448 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6449 b_type == nullptr || b_type->elem() == Type::BOTTOM ||
6450 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6451 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6452 // failed array check
6453 return false;
6454 }
6455
6456 BasicType a_elem = a_type->elem()->array_element_basic_type();
6457 BasicType b_elem = b_type->elem()->array_element_basic_type();
6458 BasicType n_elem = n_type->elem()->array_element_basic_type();
6459 BasicType m_elem = m_type->elem()->array_element_basic_type();
6460 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6461 return false;
6462 }
6463
6464 // Make the call
6465 {
6466 Node* a_start = array_element_address(a, intcon(0), a_elem);
6467 Node* b_start = array_element_address(b, intcon(0), b_elem);
6468 Node* n_start = array_element_address(n, intcon(0), n_elem);
6469 Node* m_start = array_element_address(m, intcon(0), m_elem);
6470
6471 Node* call = make_runtime_call(RC_LEAF,
6472 OptoRuntime::montgomeryMultiply_Type(),
6473 stubAddr, stubName, TypePtr::BOTTOM,
6474 a_start, b_start, n_start, len, inv, top(),
6475 m_start);
6476 set_result(m);
6477 }
6478
6479 return true;
6480 }
6481
6482 bool LibraryCallKit::inline_montgomerySquare() {
6483 address stubAddr = StubRoutines::montgomerySquare();
6484 if (stubAddr == nullptr) {
6485 return false; // Intrinsic's stub is not implemented on this platform
6486 }
6487
6488 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
6489 const char* stubName = "montgomery_square";
6490
6491 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
6492
6493 Node* a = argument(0);
6494 Node* n = argument(1);
6495 Node* len = argument(2);
6496 Node* inv = argument(3);
6497 Node* m = argument(5);
6498
6499 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6500 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6501 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6502 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6503 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6504 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6505 // failed array check
6506 return false;
6507 }
6508
6509 BasicType a_elem = a_type->elem()->array_element_basic_type();
6510 BasicType n_elem = n_type->elem()->array_element_basic_type();
6511 BasicType m_elem = m_type->elem()->array_element_basic_type();
6512 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6513 return false;
6514 }
6515
6516 // Make the call
6517 {
6518 Node* a_start = array_element_address(a, intcon(0), a_elem);
6519 Node* n_start = array_element_address(n, intcon(0), n_elem);
6520 Node* m_start = array_element_address(m, intcon(0), m_elem);
6521
6522 Node* call = make_runtime_call(RC_LEAF,
6523 OptoRuntime::montgomerySquare_Type(),
6524 stubAddr, stubName, TypePtr::BOTTOM,
6525 a_start, n_start, len, inv, top(),
6526 m_start);
6527 set_result(m);
6528 }
6529
6530 return true;
6531 }
6532
6533 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
6534 address stubAddr = nullptr;
6535 const char* stubName = nullptr;
6536
6537 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
6538 if (stubAddr == nullptr) {
6539 return false; // Intrinsic's stub is not implemented on this platform
6540 }
6541
6542 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
6543
6544 assert(callee()->signature()->size() == 5, "expected 5 arguments");
6545
6546 Node* newArr = argument(0);
6547 Node* oldArr = argument(1);
6548 Node* newIdx = argument(2);
6549 Node* shiftCount = argument(3);
6550 Node* numIter = argument(4);
6551
6552 const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
6553 const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
6554 if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
6555 oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
6556 return false;
6557 }
6558
6559 BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
6560 BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
6561 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
6562 return false;
6563 }
6564
6565 // Make the call
6566 {
6567 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
6568 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
6569
6570 Node* call = make_runtime_call(RC_LEAF,
6571 OptoRuntime::bigIntegerShift_Type(),
6572 stubAddr,
6573 stubName,
6574 TypePtr::BOTTOM,
6575 newArr_start,
6576 oldArr_start,
6577 newIdx,
6578 shiftCount,
6579 numIter);
6580 }
6581
6582 return true;
6583 }
6584
6585 //-------------inline_vectorizedMismatch------------------------------
6586 bool LibraryCallKit::inline_vectorizedMismatch() {
6587 assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
6588
6589 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
6590 Node* obja = argument(0); // Object
6591 Node* aoffset = argument(1); // long
6592 Node* objb = argument(3); // Object
6593 Node* boffset = argument(4); // long
6594 Node* length = argument(6); // int
6595 Node* scale = argument(7); // int
6596
6597 const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
6598 const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
6599 if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
6600 objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
6601 scale == top()) {
6602 return false; // failed input validation
6603 }
6604
6605 Node* obja_adr = make_unsafe_address(obja, aoffset);
6606 Node* objb_adr = make_unsafe_address(objb, boffset);
6607
6608 // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
6609 //
6610 // inline_limit = ArrayOperationPartialInlineSize / element_size;
6611 // if (length <= inline_limit) {
6612 // inline_path:
6613 // vmask = VectorMaskGen length
6614 // vload1 = LoadVectorMasked obja, vmask
6615 // vload2 = LoadVectorMasked objb, vmask
6616 // result1 = VectorCmpMasked vload1, vload2, vmask
6617 // } else {
6618 // call_stub_path:
6619 // result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
6620 // }
6621 // exit_block:
6622 // return Phi(result1, result2);
6623 //
6624 enum { inline_path = 1, // input is small enough to process it all at once
6625 stub_path = 2, // input is too large; call into the VM
6626 PATH_LIMIT = 3
6627 };
6628
6629 Node* exit_block = new RegionNode(PATH_LIMIT);
6630 Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
6631 Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
6632
6633 Node* call_stub_path = control();
6634
6635 BasicType elem_bt = T_ILLEGAL;
6636
6637 const TypeInt* scale_t = _gvn.type(scale)->is_int();
6638 if (scale_t->is_con()) {
6639 switch (scale_t->get_con()) {
6640 case 0: elem_bt = T_BYTE; break;
6641 case 1: elem_bt = T_SHORT; break;
6642 case 2: elem_bt = T_INT; break;
6643 case 3: elem_bt = T_LONG; break;
6644
6645 default: elem_bt = T_ILLEGAL; break; // not supported
6646 }
6647 }
6648
6649 int inline_limit = 0;
6650 bool do_partial_inline = false;
6651
6652 if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
6653 inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
6654 do_partial_inline = inline_limit >= 16;
6655 }
6656
6657 if (do_partial_inline) {
6658 assert(elem_bt != T_ILLEGAL, "sanity");
6659
6660 if (Matcher::match_rule_supported_vector(Op_VectorMaskGen, inline_limit, elem_bt) &&
6661 Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
6662 Matcher::match_rule_supported_vector(Op_VectorCmpMasked, inline_limit, elem_bt)) {
6663
6664 const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
6665 Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
6666 Node* bol_gt = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
6667
6668 call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
6669
6670 if (!stopped()) {
6671 Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
6672
6673 const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
6674 const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
6675 Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
6676 Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
6677
6678 Node* vmask = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
6679 Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
6680 Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
6681 Node* result = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
6682
6683 exit_block->init_req(inline_path, control());
6684 memory_phi->init_req(inline_path, map()->memory());
6685 result_phi->init_req(inline_path, result);
6686
6687 C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
6688 clear_upper_avx();
6689 }
6690 }
6691 }
6692
6693 if (call_stub_path != nullptr) {
6694 set_control(call_stub_path);
6695
6696 Node* call = make_runtime_call(RC_LEAF,
6697 OptoRuntime::vectorizedMismatch_Type(),
6698 StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
6699 obja_adr, objb_adr, length, scale);
6700
6701 exit_block->init_req(stub_path, control());
6702 memory_phi->init_req(stub_path, map()->memory());
6703 result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
6704 }
6705
6706 exit_block = _gvn.transform(exit_block);
6707 memory_phi = _gvn.transform(memory_phi);
6708 result_phi = _gvn.transform(result_phi);
6709
6710 record_for_igvn(exit_block);
6711 record_for_igvn(memory_phi);
6712 record_for_igvn(result_phi);
6713
6714 set_control(exit_block);
6715 set_all_memory(memory_phi);
6716 set_result(result_phi);
6717
6718 return true;
6719 }
6720
6721 //------------------------------inline_vectorizedHashcode----------------------------
6722 bool LibraryCallKit::inline_vectorizedHashCode() {
6723 assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
6724
6725 assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
6726 Node* array = argument(0);
6727 Node* offset = argument(1);
6728 Node* length = argument(2);
6729 Node* initialValue = argument(3);
6730 Node* basic_type = argument(4);
6731
6732 if (basic_type == top()) {
6733 return false; // failed input validation
6734 }
6735
6736 const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
6737 if (!basic_type_t->is_con()) {
6738 return false; // Only intrinsify if mode argument is constant
6739 }
6740
6741 array = must_be_not_null(array, true);
6742
6743 BasicType bt = (BasicType)basic_type_t->get_con();
6744
6745 // Resolve address of first element
6746 Node* array_start = array_element_address(array, offset, bt);
6747
6748 const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
6749 set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
6750 array_start, length, initialValue, basic_type)));
6751 clear_upper_avx();
6752
6753 return true;
6754 }
6755
6756 /**
6757 * Calculate CRC32 for byte.
6758 * int java.util.zip.CRC32.update(int crc, int b)
6759 */
6760 bool LibraryCallKit::inline_updateCRC32() {
6761 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6762 assert(callee()->signature()->size() == 2, "update has 2 parameters");
6763 // no receiver since it is static method
6764 Node* crc = argument(0); // type: int
6765 Node* b = argument(1); // type: int
6766
6767 /*
6768 * int c = ~ crc;
6769 * b = timesXtoThe32[(b ^ c) & 0xFF];
6770 * b = b ^ (c >>> 8);
6771 * crc = ~b;
6772 */
6773
6774 Node* M1 = intcon(-1);
6775 crc = _gvn.transform(new XorINode(crc, M1));
6776 Node* result = _gvn.transform(new XorINode(crc, b));
6777 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
6778
6779 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
6780 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
6781 Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
6782 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
6783
6784 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
6785 result = _gvn.transform(new XorINode(crc, result));
6786 result = _gvn.transform(new XorINode(result, M1));
6787 set_result(result);
6788 return true;
6789 }
6790
6791 /**
6792 * Calculate CRC32 for byte[] array.
6793 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
6794 */
6795 bool LibraryCallKit::inline_updateBytesCRC32() {
6796 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6797 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6798 // no receiver since it is static method
6799 Node* crc = argument(0); // type: int
6800 Node* src = argument(1); // type: oop
6801 Node* offset = argument(2); // type: int
6802 Node* length = argument(3); // type: int
6803
6804 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6805 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6806 // failed array check
6807 return false;
6808 }
6809
6810 // Figure out the size and type of the elements we will be copying.
6811 BasicType src_elem = src_type->elem()->array_element_basic_type();
6812 if (src_elem != T_BYTE) {
6813 return false;
6814 }
6815
6816 // 'src_start' points to src array + scaled offset
6817 src = must_be_not_null(src, true);
6818 Node* src_start = array_element_address(src, offset, src_elem);
6819
6820 // We assume that range check is done by caller.
6821 // TODO: generate range check (offset+length < src.length) in debug VM.
6822
6823 // Call the stub.
6824 address stubAddr = StubRoutines::updateBytesCRC32();
6825 const char *stubName = "updateBytesCRC32";
6826
6827 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6828 stubAddr, stubName, TypePtr::BOTTOM,
6829 crc, src_start, length);
6830 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6831 set_result(result);
6832 return true;
6833 }
6834
6835 /**
6836 * Calculate CRC32 for ByteBuffer.
6837 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
6838 */
6839 bool LibraryCallKit::inline_updateByteBufferCRC32() {
6840 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6841 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6842 // no receiver since it is static method
6843 Node* crc = argument(0); // type: int
6844 Node* src = argument(1); // type: long
6845 Node* offset = argument(3); // type: int
6846 Node* length = argument(4); // type: int
6847
6848 src = ConvL2X(src); // adjust Java long to machine word
6849 Node* base = _gvn.transform(new CastX2PNode(src));
6850 offset = ConvI2X(offset);
6851
6852 // 'src_start' points to src array + scaled offset
6853 Node* src_start = off_heap_plus_addr(base, offset);
6854
6855 // Call the stub.
6856 address stubAddr = StubRoutines::updateBytesCRC32();
6857 const char *stubName = "updateBytesCRC32";
6858
6859 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6860 stubAddr, stubName, TypePtr::BOTTOM,
6861 crc, src_start, length);
6862 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6863 set_result(result);
6864 return true;
6865 }
6866
6867 //------------------------------get_table_from_crc32c_class-----------------------
6868 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
6869 Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
6870 assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
6871
6872 return table;
6873 }
6874
6875 //------------------------------inline_updateBytesCRC32C-----------------------
6876 //
6877 // Calculate CRC32C for byte[] array.
6878 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
6879 //
6880 bool LibraryCallKit::inline_updateBytesCRC32C() {
6881 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6882 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6883 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6884 // no receiver since it is a static method
6885 Node* crc = argument(0); // type: int
6886 Node* src = argument(1); // type: oop
6887 Node* offset = argument(2); // type: int
6888 Node* end = argument(3); // type: int
6889
6890 Node* length = _gvn.transform(new SubINode(end, offset));
6891
6892 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6893 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6894 // failed array check
6895 return false;
6896 }
6897
6898 // Figure out the size and type of the elements we will be copying.
6899 BasicType src_elem = src_type->elem()->array_element_basic_type();
6900 if (src_elem != T_BYTE) {
6901 return false;
6902 }
6903
6904 // 'src_start' points to src array + scaled offset
6905 src = must_be_not_null(src, true);
6906 Node* src_start = array_element_address(src, offset, src_elem);
6907
6908 // static final int[] byteTable in class CRC32C
6909 Node* table = get_table_from_crc32c_class(callee()->holder());
6910 table = must_be_not_null(table, true);
6911 Node* table_start = array_element_address(table, intcon(0), T_INT);
6912
6913 // We assume that range check is done by caller.
6914 // TODO: generate range check (offset+length < src.length) in debug VM.
6915
6916 // Call the stub.
6917 address stubAddr = StubRoutines::updateBytesCRC32C();
6918 const char *stubName = "updateBytesCRC32C";
6919
6920 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6921 stubAddr, stubName, TypePtr::BOTTOM,
6922 crc, src_start, length, table_start);
6923 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6924 set_result(result);
6925 return true;
6926 }
6927
6928 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
6929 //
6930 // Calculate CRC32C for DirectByteBuffer.
6931 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
6932 //
6933 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
6934 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6935 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
6936 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6937 // no receiver since it is a static method
6938 Node* crc = argument(0); // type: int
6939 Node* src = argument(1); // type: long
6940 Node* offset = argument(3); // type: int
6941 Node* end = argument(4); // type: int
6942
6943 Node* length = _gvn.transform(new SubINode(end, offset));
6944
6945 src = ConvL2X(src); // adjust Java long to machine word
6946 Node* base = _gvn.transform(new CastX2PNode(src));
6947 offset = ConvI2X(offset);
6948
6949 // 'src_start' points to src array + scaled offset
6950 Node* src_start = off_heap_plus_addr(base, offset);
6951
6952 // static final int[] byteTable in class CRC32C
6953 Node* table = get_table_from_crc32c_class(callee()->holder());
6954 table = must_be_not_null(table, true);
6955 Node* table_start = array_element_address(table, intcon(0), T_INT);
6956
6957 // Call the stub.
6958 address stubAddr = StubRoutines::updateBytesCRC32C();
6959 const char *stubName = "updateBytesCRC32C";
6960
6961 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6962 stubAddr, stubName, TypePtr::BOTTOM,
6963 crc, src_start, length, table_start);
6964 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6965 set_result(result);
6966 return true;
6967 }
6968
6969 //------------------------------inline_updateBytesAdler32----------------------
6970 //
6971 // Calculate Adler32 checksum for byte[] array.
6972 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
6973 //
6974 bool LibraryCallKit::inline_updateBytesAdler32() {
6975 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6976 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6977 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6978 // no receiver since it is static method
6979 Node* crc = argument(0); // type: int
6980 Node* src = argument(1); // type: oop
6981 Node* offset = argument(2); // type: int
6982 Node* length = argument(3); // type: int
6983
6984 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6985 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6986 // failed array check
6987 return false;
6988 }
6989
6990 // Figure out the size and type of the elements we will be copying.
6991 BasicType src_elem = src_type->elem()->array_element_basic_type();
6992 if (src_elem != T_BYTE) {
6993 return false;
6994 }
6995
6996 // 'src_start' points to src array + scaled offset
6997 Node* src_start = array_element_address(src, offset, src_elem);
6998
6999 // We assume that range check is done by caller.
7000 // TODO: generate range check (offset+length < src.length) in debug VM.
7001
7002 // Call the stub.
7003 address stubAddr = StubRoutines::updateBytesAdler32();
7004 const char *stubName = "updateBytesAdler32";
7005
7006 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7007 stubAddr, stubName, TypePtr::BOTTOM,
7008 crc, src_start, length);
7009 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7010 set_result(result);
7011 return true;
7012 }
7013
7014 //------------------------------inline_updateByteBufferAdler32---------------
7015 //
7016 // Calculate Adler32 checksum for DirectByteBuffer.
7017 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7018 //
7019 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7020 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7021 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7022 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7023 // no receiver since it is static method
7024 Node* crc = argument(0); // type: int
7025 Node* src = argument(1); // type: long
7026 Node* offset = argument(3); // type: int
7027 Node* length = argument(4); // type: int
7028
7029 src = ConvL2X(src); // adjust Java long to machine word
7030 Node* base = _gvn.transform(new CastX2PNode(src));
7031 offset = ConvI2X(offset);
7032
7033 // 'src_start' points to src array + scaled offset
7034 Node* src_start = off_heap_plus_addr(base, offset);
7035
7036 // Call the stub.
7037 address stubAddr = StubRoutines::updateBytesAdler32();
7038 const char *stubName = "updateBytesAdler32";
7039
7040 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7041 stubAddr, stubName, TypePtr::BOTTOM,
7042 crc, src_start, length);
7043
7044 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7045 set_result(result);
7046 return true;
7047 }
7048
7049 //----------------------------inline_reference_get0----------------------------
7050 // public T java.lang.ref.Reference.get();
7051 bool LibraryCallKit::inline_reference_get0() {
7052 const int referent_offset = java_lang_ref_Reference::referent_offset();
7053
7054 // Get the argument:
7055 Node* reference_obj = null_check_receiver();
7056 if (stopped()) return true;
7057
7058 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7059 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7060 decorators, /*is_static*/ false,
7061 env()->Reference_klass());
7062 if (result == nullptr) return false;
7063
7064 // Add memory barrier to prevent commoning reads from this field
7065 // across safepoint since GC can change its value.
7066 insert_mem_bar(Op_MemBarCPUOrder);
7067
7068 set_result(result);
7069 return true;
7070 }
7071
7072 //----------------------------inline_reference_refersTo0----------------------------
7073 // bool java.lang.ref.Reference.refersTo0();
7074 // bool java.lang.ref.PhantomReference.refersTo0();
7075 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7076 // Get arguments:
7077 Node* reference_obj = null_check_receiver();
7078 Node* other_obj = argument(1);
7079 if (stopped()) return true;
7080
7081 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7082 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7083 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7084 decorators, /*is_static*/ false,
7085 env()->Reference_klass());
7086 if (referent == nullptr) return false;
7087
7088 // Add memory barrier to prevent commoning reads from this field
7089 // across safepoint since GC can change its value.
7090 insert_mem_bar(Op_MemBarCPUOrder);
7091
7092 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7093 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7094 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7095
7096 RegionNode* region = new RegionNode(3);
7097 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7098
7099 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7100 region->init_req(1, if_true);
7101 phi->init_req(1, intcon(1));
7102
7103 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7104 region->init_req(2, if_false);
7105 phi->init_req(2, intcon(0));
7106
7107 set_control(_gvn.transform(region));
7108 record_for_igvn(region);
7109 set_result(_gvn.transform(phi));
7110 return true;
7111 }
7112
7113 //----------------------------inline_reference_clear0----------------------------
7114 // void java.lang.ref.Reference.clear0();
7115 // void java.lang.ref.PhantomReference.clear0();
7116 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7117 // This matches the implementation in JVM_ReferenceClear, see the comments there.
7118
7119 // Get arguments
7120 Node* reference_obj = null_check_receiver();
7121 if (stopped()) return true;
7122
7123 // Common access parameters
7124 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7125 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7126 Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7127 const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7128 const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7129
7130 Node* referent = access_load_at(reference_obj,
7131 referent_field_addr,
7132 referent_field_addr_type,
7133 val_type,
7134 T_OBJECT,
7135 decorators);
7136
7137 IdealKit ideal(this);
7138 #define __ ideal.
7139 __ if_then(referent, BoolTest::ne, null());
7140 sync_kit(ideal);
7141 access_store_at(reference_obj,
7142 referent_field_addr,
7143 referent_field_addr_type,
7144 null(),
7145 val_type,
7146 T_OBJECT,
7147 decorators);
7148 __ sync_kit(this);
7149 __ end_if();
7150 final_sync(ideal);
7151 #undef __
7152
7153 return true;
7154 }
7155
7156 //-----------------------inline_reference_reachabilityFence-----------------
7157 // bool java.lang.ref.Reference.reachabilityFence();
7158 bool LibraryCallKit::inline_reference_reachabilityFence() {
7159 Node* referent = argument(0);
7160 insert_reachability_fence(referent);
7161 return true;
7162 }
7163
7164 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7165 DecoratorSet decorators, bool is_static,
7166 ciInstanceKlass* fromKls) {
7167 if (fromKls == nullptr) {
7168 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7169 assert(tinst != nullptr, "obj is null");
7170 assert(tinst->is_loaded(), "obj is not loaded");
7171 fromKls = tinst->instance_klass();
7172 }
7173 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7174 ciSymbol::make(fieldTypeString),
7175 is_static);
7176
7177 assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7178 if (field == nullptr) return (Node *) nullptr;
7179
7180 if (is_static) {
7181 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7182 fromObj = makecon(tip);
7183 }
7184
7185 // Next code copied from Parse::do_get_xxx():
7186
7187 // Compute address and memory type.
7188 int offset = field->offset_in_bytes();
7189 bool is_vol = field->is_volatile();
7190 ciType* field_klass = field->type();
7191 assert(field_klass->is_loaded(), "should be loaded");
7192 const TypePtr* adr_type = C->alias_type(field)->adr_type();
7193 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7194 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7195 "slice of address and input slice don't match");
7196 BasicType bt = field->layout_type();
7197
7198 // Build the resultant type of the load
7199 const Type *type;
7200 if (bt == T_OBJECT) {
7201 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7202 } else {
7203 type = Type::get_const_basic_type(bt);
7204 }
7205
7206 if (is_vol) {
7207 decorators |= MO_SEQ_CST;
7208 }
7209
7210 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7211 }
7212
7213 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7214 bool is_exact /* true */, bool is_static /* false */,
7215 ciInstanceKlass * fromKls /* nullptr */) {
7216 if (fromKls == nullptr) {
7217 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7218 assert(tinst != nullptr, "obj is null");
7219 assert(tinst->is_loaded(), "obj is not loaded");
7220 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7221 fromKls = tinst->instance_klass();
7222 }
7223 else {
7224 assert(is_static, "only for static field access");
7225 }
7226 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7227 ciSymbol::make(fieldTypeString),
7228 is_static);
7229
7230 assert(field != nullptr, "undefined field");
7231 assert(!field->is_volatile(), "not defined for volatile fields");
7232
7233 if (is_static) {
7234 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7235 fromObj = makecon(tip);
7236 }
7237
7238 // Next code copied from Parse::do_get_xxx():
7239
7240 // Compute address and memory type.
7241 int offset = field->offset_in_bytes();
7242 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7243
7244 return adr;
7245 }
7246
7247 //------------------------------inline_aescrypt_Block-----------------------
7248 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7249 address stubAddr = nullptr;
7250 const char *stubName;
7251 bool is_decrypt = false;
7252 assert(UseAES, "need AES instruction support");
7253
7254 switch(id) {
7255 case vmIntrinsics::_aescrypt_encryptBlock:
7256 stubAddr = StubRoutines::aescrypt_encryptBlock();
7257 stubName = "aescrypt_encryptBlock";
7258 break;
7259 case vmIntrinsics::_aescrypt_decryptBlock:
7260 stubAddr = StubRoutines::aescrypt_decryptBlock();
7261 stubName = "aescrypt_decryptBlock";
7262 is_decrypt = true;
7263 break;
7264 default:
7265 break;
7266 }
7267 if (stubAddr == nullptr) return false;
7268
7269 Node* aescrypt_object = argument(0);
7270 Node* src = argument(1);
7271 Node* src_offset = argument(2);
7272 Node* dest = argument(3);
7273 Node* dest_offset = argument(4);
7274
7275 src = must_be_not_null(src, true);
7276 dest = must_be_not_null(dest, true);
7277
7278 // (1) src and dest are arrays.
7279 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7280 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7281 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7282 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7283
7284 // for the quick and dirty code we will skip all the checks.
7285 // we are just trying to get the call to be generated.
7286 Node* src_start = src;
7287 Node* dest_start = dest;
7288 if (src_offset != nullptr || dest_offset != nullptr) {
7289 assert(src_offset != nullptr && dest_offset != nullptr, "");
7290 src_start = array_element_address(src, src_offset, T_BYTE);
7291 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7292 }
7293
7294 // now need to get the start of its expanded key array
7295 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7296 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7297 if (k_start == nullptr) return false;
7298
7299 // Call the stub.
7300 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7301 stubAddr, stubName, TypePtr::BOTTOM,
7302 src_start, dest_start, k_start);
7303
7304 return true;
7305 }
7306
7307 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7308 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7309 address stubAddr = nullptr;
7310 const char *stubName = nullptr;
7311 bool is_decrypt = false;
7312 assert(UseAES, "need AES instruction support");
7313
7314 switch(id) {
7315 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7316 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7317 stubName = "cipherBlockChaining_encryptAESCrypt";
7318 break;
7319 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7320 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7321 stubName = "cipherBlockChaining_decryptAESCrypt";
7322 is_decrypt = true;
7323 break;
7324 default:
7325 break;
7326 }
7327 if (stubAddr == nullptr) return false;
7328
7329 Node* cipherBlockChaining_object = argument(0);
7330 Node* src = argument(1);
7331 Node* src_offset = argument(2);
7332 Node* len = argument(3);
7333 Node* dest = argument(4);
7334 Node* dest_offset = argument(5);
7335
7336 src = must_be_not_null(src, false);
7337 dest = must_be_not_null(dest, false);
7338
7339 // (1) src and dest are arrays.
7340 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7341 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7342 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7343 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7344
7345 // checks are the responsibility of the caller
7346 Node* src_start = src;
7347 Node* dest_start = dest;
7348 if (src_offset != nullptr || dest_offset != nullptr) {
7349 assert(src_offset != nullptr && dest_offset != nullptr, "");
7350 src_start = array_element_address(src, src_offset, T_BYTE);
7351 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7352 }
7353
7354 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7355 // (because of the predicated logic executed earlier).
7356 // so we cast it here safely.
7357 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7358
7359 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7360 if (embeddedCipherObj == nullptr) return false;
7361
7362 // cast it to what we know it will be at runtime
7363 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7364 assert(tinst != nullptr, "CBC obj is null");
7365 assert(tinst->is_loaded(), "CBC obj is not loaded");
7366 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7367 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7368
7369 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7370 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7371 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7372 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7373 aescrypt_object = _gvn.transform(aescrypt_object);
7374
7375 // we need to get the start of the aescrypt_object's expanded key array
7376 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7377 if (k_start == nullptr) return false;
7378
7379 // similarly, get the start address of the r vector
7380 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7381 if (objRvec == nullptr) return false;
7382 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7383
7384 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7385 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7386 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7387 stubAddr, stubName, TypePtr::BOTTOM,
7388 src_start, dest_start, k_start, r_start, len);
7389
7390 // return cipher length (int)
7391 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7392 set_result(retvalue);
7393 return true;
7394 }
7395
7396 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7397 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7398 address stubAddr = nullptr;
7399 const char *stubName = nullptr;
7400 bool is_decrypt = false;
7401 assert(UseAES, "need AES instruction support");
7402
7403 switch (id) {
7404 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7405 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7406 stubName = "electronicCodeBook_encryptAESCrypt";
7407 break;
7408 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7409 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7410 stubName = "electronicCodeBook_decryptAESCrypt";
7411 is_decrypt = true;
7412 break;
7413 default:
7414 break;
7415 }
7416
7417 if (stubAddr == nullptr) return false;
7418
7419 Node* electronicCodeBook_object = argument(0);
7420 Node* src = argument(1);
7421 Node* src_offset = argument(2);
7422 Node* len = argument(3);
7423 Node* dest = argument(4);
7424 Node* dest_offset = argument(5);
7425
7426 // (1) src and dest are arrays.
7427 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7428 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7429 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7430 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7431
7432 // checks are the responsibility of the caller
7433 Node* src_start = src;
7434 Node* dest_start = dest;
7435 if (src_offset != nullptr || dest_offset != nullptr) {
7436 assert(src_offset != nullptr && dest_offset != nullptr, "");
7437 src_start = array_element_address(src, src_offset, T_BYTE);
7438 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7439 }
7440
7441 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7442 // (because of the predicated logic executed earlier).
7443 // so we cast it here safely.
7444 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7445
7446 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7447 if (embeddedCipherObj == nullptr) return false;
7448
7449 // cast it to what we know it will be at runtime
7450 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7451 assert(tinst != nullptr, "ECB obj is null");
7452 assert(tinst->is_loaded(), "ECB obj is not loaded");
7453 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7454 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7455
7456 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7457 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7458 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7459 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7460 aescrypt_object = _gvn.transform(aescrypt_object);
7461
7462 // we need to get the start of the aescrypt_object's expanded key array
7463 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7464 if (k_start == nullptr) return false;
7465
7466 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7467 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
7468 OptoRuntime::electronicCodeBook_aescrypt_Type(),
7469 stubAddr, stubName, TypePtr::BOTTOM,
7470 src_start, dest_start, k_start, len);
7471
7472 // return cipher length (int)
7473 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
7474 set_result(retvalue);
7475 return true;
7476 }
7477
7478 //------------------------------inline_counterMode_AESCrypt-----------------------
7479 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
7480 assert(UseAES, "need AES instruction support");
7481 if (!UseAESCTRIntrinsics) return false;
7482
7483 address stubAddr = nullptr;
7484 const char *stubName = nullptr;
7485 if (id == vmIntrinsics::_counterMode_AESCrypt) {
7486 stubAddr = StubRoutines::counterMode_AESCrypt();
7487 stubName = "counterMode_AESCrypt";
7488 }
7489 if (stubAddr == nullptr) return false;
7490
7491 Node* counterMode_object = argument(0);
7492 Node* src = argument(1);
7493 Node* src_offset = argument(2);
7494 Node* len = argument(3);
7495 Node* dest = argument(4);
7496 Node* dest_offset = argument(5);
7497
7498 // (1) src and dest are arrays.
7499 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7500 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7501 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7502 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7503
7504 // checks are the responsibility of the caller
7505 Node* src_start = src;
7506 Node* dest_start = dest;
7507 if (src_offset != nullptr || dest_offset != nullptr) {
7508 assert(src_offset != nullptr && dest_offset != nullptr, "");
7509 src_start = array_element_address(src, src_offset, T_BYTE);
7510 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7511 }
7512
7513 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7514 // (because of the predicated logic executed earlier).
7515 // so we cast it here safely.
7516 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7517 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7518 if (embeddedCipherObj == nullptr) return false;
7519 // cast it to what we know it will be at runtime
7520 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
7521 assert(tinst != nullptr, "CTR obj is null");
7522 assert(tinst->is_loaded(), "CTR obj is not loaded");
7523 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7524 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7525 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7526 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7527 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7528 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7529 aescrypt_object = _gvn.transform(aescrypt_object);
7530 // we need to get the start of the aescrypt_object's expanded key array
7531 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
7532 if (k_start == nullptr) return false;
7533 // similarly, get the start address of the r vector
7534 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
7535 if (obj_counter == nullptr) return false;
7536 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
7537
7538 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
7539 if (saved_encCounter == nullptr) return false;
7540 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
7541 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
7542
7543 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7544 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7545 OptoRuntime::counterMode_aescrypt_Type(),
7546 stubAddr, stubName, TypePtr::BOTTOM,
7547 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
7548
7549 // return cipher length (int)
7550 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
7551 set_result(retvalue);
7552 return true;
7553 }
7554
7555 //------------------------------get_key_start_from_aescrypt_object-----------------------
7556 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
7557 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
7558 // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
7559 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
7560 // The following platform specific stubs of encryption and decryption use the same round keys.
7561 #if defined(PPC64) || defined(S390) || defined(RISCV64)
7562 bool use_decryption_key = false;
7563 #else
7564 bool use_decryption_key = is_decrypt;
7565 #endif
7566 Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
7567 assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
7568 if (objAESCryptKey == nullptr) return (Node *) nullptr;
7569
7570 // now have the array, need to get the start address of the selected key array
7571 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
7572 return k_start;
7573 }
7574
7575 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
7576 // Return node representing slow path of predicate check.
7577 // the pseudo code we want to emulate with this predicate is:
7578 // for encryption:
7579 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7580 // for decryption:
7581 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7582 // note cipher==plain is more conservative than the original java code but that's OK
7583 //
7584 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
7585 // The receiver was checked for null already.
7586 Node* objCBC = argument(0);
7587
7588 Node* src = argument(1);
7589 Node* dest = argument(4);
7590
7591 // Load embeddedCipher field of CipherBlockChaining object.
7592 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7593
7594 // get AESCrypt klass for instanceOf check
7595 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7596 // will have same classloader as CipherBlockChaining object
7597 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
7598 assert(tinst != nullptr, "CBCobj is null");
7599 assert(tinst->is_loaded(), "CBCobj is not loaded");
7600
7601 // we want to do an instanceof comparison against the AESCrypt class
7602 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7603 if (!klass_AESCrypt->is_loaded()) {
7604 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7605 Node* ctrl = control();
7606 set_control(top()); // no regular fast path
7607 return ctrl;
7608 }
7609
7610 src = must_be_not_null(src, true);
7611 dest = must_be_not_null(dest, true);
7612
7613 // Resolve oops to stable for CmpP below.
7614 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7615
7616 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7617 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7618 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7619
7620 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7621
7622 // for encryption, we are done
7623 if (!decrypting)
7624 return instof_false; // even if it is null
7625
7626 // for decryption, we need to add a further check to avoid
7627 // taking the intrinsic path when cipher and plain are the same
7628 // see the original java code for why.
7629 RegionNode* region = new RegionNode(3);
7630 region->init_req(1, instof_false);
7631
7632 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7633 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7634 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7635 region->init_req(2, src_dest_conjoint);
7636
7637 record_for_igvn(region);
7638 return _gvn.transform(region);
7639 }
7640
7641 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
7642 // Return node representing slow path of predicate check.
7643 // the pseudo code we want to emulate with this predicate is:
7644 // for encryption:
7645 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7646 // for decryption:
7647 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7648 // note cipher==plain is more conservative than the original java code but that's OK
7649 //
7650 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
7651 // The receiver was checked for null already.
7652 Node* objECB = argument(0);
7653
7654 // Load embeddedCipher field of ElectronicCodeBook object.
7655 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7656
7657 // get AESCrypt klass for instanceOf check
7658 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7659 // will have same classloader as ElectronicCodeBook object
7660 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
7661 assert(tinst != nullptr, "ECBobj is null");
7662 assert(tinst->is_loaded(), "ECBobj is not loaded");
7663
7664 // we want to do an instanceof comparison against the AESCrypt class
7665 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7666 if (!klass_AESCrypt->is_loaded()) {
7667 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7668 Node* ctrl = control();
7669 set_control(top()); // no regular fast path
7670 return ctrl;
7671 }
7672 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7673
7674 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7675 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7676 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7677
7678 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7679
7680 // for encryption, we are done
7681 if (!decrypting)
7682 return instof_false; // even if it is null
7683
7684 // for decryption, we need to add a further check to avoid
7685 // taking the intrinsic path when cipher and plain are the same
7686 // see the original java code for why.
7687 RegionNode* region = new RegionNode(3);
7688 region->init_req(1, instof_false);
7689 Node* src = argument(1);
7690 Node* dest = argument(4);
7691 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7692 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7693 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7694 region->init_req(2, src_dest_conjoint);
7695
7696 record_for_igvn(region);
7697 return _gvn.transform(region);
7698 }
7699
7700 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
7701 // Return node representing slow path of predicate check.
7702 // the pseudo code we want to emulate with this predicate is:
7703 // for encryption:
7704 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7705 // for decryption:
7706 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7707 // note cipher==plain is more conservative than the original java code but that's OK
7708 //
7709
7710 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
7711 // The receiver was checked for null already.
7712 Node* objCTR = argument(0);
7713
7714 // Load embeddedCipher field of CipherBlockChaining object.
7715 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7716
7717 // get AESCrypt klass for instanceOf check
7718 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7719 // will have same classloader as CipherBlockChaining object
7720 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
7721 assert(tinst != nullptr, "CTRobj is null");
7722 assert(tinst->is_loaded(), "CTRobj is not loaded");
7723
7724 // we want to do an instanceof comparison against the AESCrypt class
7725 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7726 if (!klass_AESCrypt->is_loaded()) {
7727 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7728 Node* ctrl = control();
7729 set_control(top()); // no regular fast path
7730 return ctrl;
7731 }
7732
7733 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7734 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7735 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7736 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7737 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7738
7739 return instof_false; // even if it is null
7740 }
7741
7742 //------------------------------inline_ghash_processBlocks
7743 bool LibraryCallKit::inline_ghash_processBlocks() {
7744 address stubAddr;
7745 const char *stubName;
7746 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
7747
7748 stubAddr = StubRoutines::ghash_processBlocks();
7749 stubName = "ghash_processBlocks";
7750
7751 Node* data = argument(0);
7752 Node* offset = argument(1);
7753 Node* len = argument(2);
7754 Node* state = argument(3);
7755 Node* subkeyH = argument(4);
7756
7757 state = must_be_not_null(state, true);
7758 subkeyH = must_be_not_null(subkeyH, true);
7759 data = must_be_not_null(data, true);
7760
7761 Node* state_start = array_element_address(state, intcon(0), T_LONG);
7762 assert(state_start, "state is null");
7763 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
7764 assert(subkeyH_start, "subkeyH is null");
7765 Node* data_start = array_element_address(data, offset, T_BYTE);
7766 assert(data_start, "data is null");
7767
7768 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
7769 OptoRuntime::ghash_processBlocks_Type(),
7770 stubAddr, stubName, TypePtr::BOTTOM,
7771 state_start, subkeyH_start, data_start, len);
7772 return true;
7773 }
7774
7775 //------------------------------inline_chacha20Block
7776 bool LibraryCallKit::inline_chacha20Block() {
7777 address stubAddr;
7778 const char *stubName;
7779 assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
7780
7781 stubAddr = StubRoutines::chacha20Block();
7782 stubName = "chacha20Block";
7783
7784 Node* state = argument(0);
7785 Node* result = argument(1);
7786
7787 state = must_be_not_null(state, true);
7788 result = must_be_not_null(result, true);
7789
7790 Node* state_start = array_element_address(state, intcon(0), T_INT);
7791 assert(state_start, "state is null");
7792 Node* result_start = array_element_address(result, intcon(0), T_BYTE);
7793 assert(result_start, "result is null");
7794
7795 Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
7796 OptoRuntime::chacha20Block_Type(),
7797 stubAddr, stubName, TypePtr::BOTTOM,
7798 state_start, result_start);
7799 // return key stream length (int)
7800 Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
7801 set_result(retvalue);
7802 return true;
7803 }
7804
7805 //------------------------------inline_kyberNtt
7806 bool LibraryCallKit::inline_kyberNtt() {
7807 address stubAddr;
7808 const char *stubName;
7809 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7810 assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
7811
7812 stubAddr = StubRoutines::kyberNtt();
7813 stubName = "kyberNtt";
7814 if (!stubAddr) return false;
7815
7816 Node* coeffs = argument(0);
7817 Node* ntt_zetas = argument(1);
7818
7819 coeffs = must_be_not_null(coeffs, true);
7820 ntt_zetas = must_be_not_null(ntt_zetas, true);
7821
7822 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
7823 assert(coeffs_start, "coeffs is null");
7824 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_SHORT);
7825 assert(ntt_zetas_start, "ntt_zetas is null");
7826 Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7827 OptoRuntime::kyberNtt_Type(),
7828 stubAddr, stubName, TypePtr::BOTTOM,
7829 coeffs_start, ntt_zetas_start);
7830 // return an int
7831 Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
7832 set_result(retvalue);
7833 return true;
7834 }
7835
7836 //------------------------------inline_kyberInverseNtt
7837 bool LibraryCallKit::inline_kyberInverseNtt() {
7838 address stubAddr;
7839 const char *stubName;
7840 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7841 assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
7842
7843 stubAddr = StubRoutines::kyberInverseNtt();
7844 stubName = "kyberInverseNtt";
7845 if (!stubAddr) return false;
7846
7847 Node* coeffs = argument(0);
7848 Node* zetas = argument(1);
7849
7850 coeffs = must_be_not_null(coeffs, true);
7851 zetas = must_be_not_null(zetas, true);
7852
7853 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
7854 assert(coeffs_start, "coeffs is null");
7855 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
7856 assert(zetas_start, "inverseNtt_zetas is null");
7857 Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7858 OptoRuntime::kyberInverseNtt_Type(),
7859 stubAddr, stubName, TypePtr::BOTTOM,
7860 coeffs_start, zetas_start);
7861
7862 // return an int
7863 Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
7864 set_result(retvalue);
7865 return true;
7866 }
7867
7868 //------------------------------inline_kyberNttMult
7869 bool LibraryCallKit::inline_kyberNttMult() {
7870 address stubAddr;
7871 const char *stubName;
7872 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7873 assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
7874
7875 stubAddr = StubRoutines::kyberNttMult();
7876 stubName = "kyberNttMult";
7877 if (!stubAddr) return false;
7878
7879 Node* result = argument(0);
7880 Node* ntta = argument(1);
7881 Node* nttb = argument(2);
7882 Node* zetas = argument(3);
7883
7884 result = must_be_not_null(result, true);
7885 ntta = must_be_not_null(ntta, true);
7886 nttb = must_be_not_null(nttb, true);
7887 zetas = must_be_not_null(zetas, true);
7888
7889 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7890 assert(result_start, "result is null");
7891 Node* ntta_start = array_element_address(ntta, intcon(0), T_SHORT);
7892 assert(ntta_start, "ntta is null");
7893 Node* nttb_start = array_element_address(nttb, intcon(0), T_SHORT);
7894 assert(nttb_start, "nttb is null");
7895 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
7896 assert(zetas_start, "nttMult_zetas is null");
7897 Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
7898 OptoRuntime::kyberNttMult_Type(),
7899 stubAddr, stubName, TypePtr::BOTTOM,
7900 result_start, ntta_start, nttb_start,
7901 zetas_start);
7902
7903 // return an int
7904 Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
7905 set_result(retvalue);
7906
7907 return true;
7908 }
7909
7910 //------------------------------inline_kyberAddPoly_2
7911 bool LibraryCallKit::inline_kyberAddPoly_2() {
7912 address stubAddr;
7913 const char *stubName;
7914 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7915 assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
7916
7917 stubAddr = StubRoutines::kyberAddPoly_2();
7918 stubName = "kyberAddPoly_2";
7919 if (!stubAddr) return false;
7920
7921 Node* result = argument(0);
7922 Node* a = argument(1);
7923 Node* b = argument(2);
7924
7925 result = must_be_not_null(result, true);
7926 a = must_be_not_null(a, true);
7927 b = must_be_not_null(b, true);
7928
7929 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7930 assert(result_start, "result is null");
7931 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
7932 assert(a_start, "a is null");
7933 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
7934 assert(b_start, "b is null");
7935 Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
7936 OptoRuntime::kyberAddPoly_2_Type(),
7937 stubAddr, stubName, TypePtr::BOTTOM,
7938 result_start, a_start, b_start);
7939 // return an int
7940 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
7941 set_result(retvalue);
7942 return true;
7943 }
7944
7945 //------------------------------inline_kyberAddPoly_3
7946 bool LibraryCallKit::inline_kyberAddPoly_3() {
7947 address stubAddr;
7948 const char *stubName;
7949 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7950 assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
7951
7952 stubAddr = StubRoutines::kyberAddPoly_3();
7953 stubName = "kyberAddPoly_3";
7954 if (!stubAddr) return false;
7955
7956 Node* result = argument(0);
7957 Node* a = argument(1);
7958 Node* b = argument(2);
7959 Node* c = argument(3);
7960
7961 result = must_be_not_null(result, true);
7962 a = must_be_not_null(a, true);
7963 b = must_be_not_null(b, true);
7964 c = must_be_not_null(c, true);
7965
7966 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7967 assert(result_start, "result is null");
7968 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
7969 assert(a_start, "a is null");
7970 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
7971 assert(b_start, "b is null");
7972 Node* c_start = array_element_address(c, intcon(0), T_SHORT);
7973 assert(c_start, "c is null");
7974 Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
7975 OptoRuntime::kyberAddPoly_3_Type(),
7976 stubAddr, stubName, TypePtr::BOTTOM,
7977 result_start, a_start, b_start, c_start);
7978 // return an int
7979 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
7980 set_result(retvalue);
7981 return true;
7982 }
7983
7984 //------------------------------inline_kyber12To16
7985 bool LibraryCallKit::inline_kyber12To16() {
7986 address stubAddr;
7987 const char *stubName;
7988 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7989 assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
7990
7991 stubAddr = StubRoutines::kyber12To16();
7992 stubName = "kyber12To16";
7993 if (!stubAddr) return false;
7994
7995 Node* condensed = argument(0);
7996 Node* condensedOffs = argument(1);
7997 Node* parsed = argument(2);
7998 Node* parsedLength = argument(3);
7999
8000 condensed = must_be_not_null(condensed, true);
8001 parsed = must_be_not_null(parsed, true);
8002
8003 Node* condensed_start = array_element_address(condensed, intcon(0), T_BYTE);
8004 assert(condensed_start, "condensed is null");
8005 Node* parsed_start = array_element_address(parsed, intcon(0), T_SHORT);
8006 assert(parsed_start, "parsed is null");
8007 Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8008 OptoRuntime::kyber12To16_Type(),
8009 stubAddr, stubName, TypePtr::BOTTOM,
8010 condensed_start, condensedOffs, parsed_start, parsedLength);
8011 // return an int
8012 Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8013 set_result(retvalue);
8014 return true;
8015
8016 }
8017
8018 //------------------------------inline_kyberBarrettReduce
8019 bool LibraryCallKit::inline_kyberBarrettReduce() {
8020 address stubAddr;
8021 const char *stubName;
8022 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8023 assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8024
8025 stubAddr = StubRoutines::kyberBarrettReduce();
8026 stubName = "kyberBarrettReduce";
8027 if (!stubAddr) return false;
8028
8029 Node* coeffs = argument(0);
8030
8031 coeffs = must_be_not_null(coeffs, true);
8032
8033 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8034 assert(coeffs_start, "coeffs is null");
8035 Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8036 OptoRuntime::kyberBarrettReduce_Type(),
8037 stubAddr, stubName, TypePtr::BOTTOM,
8038 coeffs_start);
8039 // return an int
8040 Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8041 set_result(retvalue);
8042 return true;
8043 }
8044
8045 //------------------------------inline_dilithiumAlmostNtt
8046 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8047 address stubAddr;
8048 const char *stubName;
8049 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8050 assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8051
8052 stubAddr = StubRoutines::dilithiumAlmostNtt();
8053 stubName = "dilithiumAlmostNtt";
8054 if (!stubAddr) return false;
8055
8056 Node* coeffs = argument(0);
8057 Node* ntt_zetas = argument(1);
8058
8059 coeffs = must_be_not_null(coeffs, true);
8060 ntt_zetas = must_be_not_null(ntt_zetas, true);
8061
8062 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8063 assert(coeffs_start, "coeffs is null");
8064 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_INT);
8065 assert(ntt_zetas_start, "ntt_zetas is null");
8066 Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8067 OptoRuntime::dilithiumAlmostNtt_Type(),
8068 stubAddr, stubName, TypePtr::BOTTOM,
8069 coeffs_start, ntt_zetas_start);
8070 // return an int
8071 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8072 set_result(retvalue);
8073 return true;
8074 }
8075
8076 //------------------------------inline_dilithiumAlmostInverseNtt
8077 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8078 address stubAddr;
8079 const char *stubName;
8080 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8081 assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8082
8083 stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8084 stubName = "dilithiumAlmostInverseNtt";
8085 if (!stubAddr) return false;
8086
8087 Node* coeffs = argument(0);
8088 Node* zetas = argument(1);
8089
8090 coeffs = must_be_not_null(coeffs, true);
8091 zetas = must_be_not_null(zetas, true);
8092
8093 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8094 assert(coeffs_start, "coeffs is null");
8095 Node* zetas_start = array_element_address(zetas, intcon(0), T_INT);
8096 assert(zetas_start, "inverseNtt_zetas is null");
8097 Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8098 OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8099 stubAddr, stubName, TypePtr::BOTTOM,
8100 coeffs_start, zetas_start);
8101 // return an int
8102 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8103 set_result(retvalue);
8104 return true;
8105 }
8106
8107 //------------------------------inline_dilithiumNttMult
8108 bool LibraryCallKit::inline_dilithiumNttMult() {
8109 address stubAddr;
8110 const char *stubName;
8111 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8112 assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8113
8114 stubAddr = StubRoutines::dilithiumNttMult();
8115 stubName = "dilithiumNttMult";
8116 if (!stubAddr) return false;
8117
8118 Node* result = argument(0);
8119 Node* ntta = argument(1);
8120 Node* nttb = argument(2);
8121 Node* zetas = argument(3);
8122
8123 result = must_be_not_null(result, true);
8124 ntta = must_be_not_null(ntta, true);
8125 nttb = must_be_not_null(nttb, true);
8126 zetas = must_be_not_null(zetas, true);
8127
8128 Node* result_start = array_element_address(result, intcon(0), T_INT);
8129 assert(result_start, "result is null");
8130 Node* ntta_start = array_element_address(ntta, intcon(0), T_INT);
8131 assert(ntta_start, "ntta is null");
8132 Node* nttb_start = array_element_address(nttb, intcon(0), T_INT);
8133 assert(nttb_start, "nttb is null");
8134 Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8135 OptoRuntime::dilithiumNttMult_Type(),
8136 stubAddr, stubName, TypePtr::BOTTOM,
8137 result_start, ntta_start, nttb_start);
8138
8139 // return an int
8140 Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8141 set_result(retvalue);
8142
8143 return true;
8144 }
8145
8146 //------------------------------inline_dilithiumMontMulByConstant
8147 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8148 address stubAddr;
8149 const char *stubName;
8150 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8151 assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8152
8153 stubAddr = StubRoutines::dilithiumMontMulByConstant();
8154 stubName = "dilithiumMontMulByConstant";
8155 if (!stubAddr) return false;
8156
8157 Node* coeffs = argument(0);
8158 Node* constant = argument(1);
8159
8160 coeffs = must_be_not_null(coeffs, true);
8161
8162 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8163 assert(coeffs_start, "coeffs is null");
8164 Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8165 OptoRuntime::dilithiumMontMulByConstant_Type(),
8166 stubAddr, stubName, TypePtr::BOTTOM,
8167 coeffs_start, constant);
8168
8169 // return an int
8170 Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8171 set_result(retvalue);
8172 return true;
8173 }
8174
8175
8176 //------------------------------inline_dilithiumDecomposePoly
8177 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8178 address stubAddr;
8179 const char *stubName;
8180 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8181 assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8182
8183 stubAddr = StubRoutines::dilithiumDecomposePoly();
8184 stubName = "dilithiumDecomposePoly";
8185 if (!stubAddr) return false;
8186
8187 Node* input = argument(0);
8188 Node* lowPart = argument(1);
8189 Node* highPart = argument(2);
8190 Node* twoGamma2 = argument(3);
8191 Node* multiplier = argument(4);
8192
8193 input = must_be_not_null(input, true);
8194 lowPart = must_be_not_null(lowPart, true);
8195 highPart = must_be_not_null(highPart, true);
8196
8197 Node* input_start = array_element_address(input, intcon(0), T_INT);
8198 assert(input_start, "input is null");
8199 Node* lowPart_start = array_element_address(lowPart, intcon(0), T_INT);
8200 assert(lowPart_start, "lowPart is null");
8201 Node* highPart_start = array_element_address(highPart, intcon(0), T_INT);
8202 assert(highPart_start, "highPart is null");
8203
8204 Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8205 OptoRuntime::dilithiumDecomposePoly_Type(),
8206 stubAddr, stubName, TypePtr::BOTTOM,
8207 input_start, lowPart_start, highPart_start,
8208 twoGamma2, multiplier);
8209
8210 // return an int
8211 Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8212 set_result(retvalue);
8213 return true;
8214 }
8215
8216 bool LibraryCallKit::inline_base64_encodeBlock() {
8217 address stubAddr;
8218 const char *stubName;
8219 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8220 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8221 stubAddr = StubRoutines::base64_encodeBlock();
8222 stubName = "encodeBlock";
8223
8224 if (!stubAddr) return false;
8225 Node* base64obj = argument(0);
8226 Node* src = argument(1);
8227 Node* offset = argument(2);
8228 Node* len = argument(3);
8229 Node* dest = argument(4);
8230 Node* dp = argument(5);
8231 Node* isURL = argument(6);
8232
8233 src = must_be_not_null(src, true);
8234 dest = must_be_not_null(dest, true);
8235
8236 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8237 assert(src_start, "source array is null");
8238 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8239 assert(dest_start, "destination array is null");
8240
8241 Node* base64 = make_runtime_call(RC_LEAF,
8242 OptoRuntime::base64_encodeBlock_Type(),
8243 stubAddr, stubName, TypePtr::BOTTOM,
8244 src_start, offset, len, dest_start, dp, isURL);
8245 return true;
8246 }
8247
8248 bool LibraryCallKit::inline_base64_decodeBlock() {
8249 address stubAddr;
8250 const char *stubName;
8251 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8252 assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8253 stubAddr = StubRoutines::base64_decodeBlock();
8254 stubName = "decodeBlock";
8255
8256 if (!stubAddr) return false;
8257 Node* base64obj = argument(0);
8258 Node* src = argument(1);
8259 Node* src_offset = argument(2);
8260 Node* len = argument(3);
8261 Node* dest = argument(4);
8262 Node* dest_offset = argument(5);
8263 Node* isURL = argument(6);
8264 Node* isMIME = argument(7);
8265
8266 src = must_be_not_null(src, true);
8267 dest = must_be_not_null(dest, true);
8268
8269 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8270 assert(src_start, "source array is null");
8271 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8272 assert(dest_start, "destination array is null");
8273
8274 Node* call = make_runtime_call(RC_LEAF,
8275 OptoRuntime::base64_decodeBlock_Type(),
8276 stubAddr, stubName, TypePtr::BOTTOM,
8277 src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8278 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8279 set_result(result);
8280 return true;
8281 }
8282
8283 bool LibraryCallKit::inline_poly1305_processBlocks() {
8284 address stubAddr;
8285 const char *stubName;
8286 assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8287 assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8288 stubAddr = StubRoutines::poly1305_processBlocks();
8289 stubName = "poly1305_processBlocks";
8290
8291 if (!stubAddr) return false;
8292 null_check_receiver(); // null-check receiver
8293 if (stopped()) return true;
8294
8295 Node* input = argument(1);
8296 Node* input_offset = argument(2);
8297 Node* len = argument(3);
8298 Node* alimbs = argument(4);
8299 Node* rlimbs = argument(5);
8300
8301 input = must_be_not_null(input, true);
8302 alimbs = must_be_not_null(alimbs, true);
8303 rlimbs = must_be_not_null(rlimbs, true);
8304
8305 Node* input_start = array_element_address(input, input_offset, T_BYTE);
8306 assert(input_start, "input array is null");
8307 Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8308 assert(acc_start, "acc array is null");
8309 Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8310 assert(r_start, "r array is null");
8311
8312 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8313 OptoRuntime::poly1305_processBlocks_Type(),
8314 stubAddr, stubName, TypePtr::BOTTOM,
8315 input_start, len, acc_start, r_start);
8316 return true;
8317 }
8318
8319 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8320 address stubAddr;
8321 const char *stubName;
8322 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8323 assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8324 stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8325 stubName = "intpoly_montgomeryMult_P256";
8326
8327 if (!stubAddr) return false;
8328 null_check_receiver(); // null-check receiver
8329 if (stopped()) return true;
8330
8331 Node* a = argument(1);
8332 Node* b = argument(2);
8333 Node* r = argument(3);
8334
8335 a = must_be_not_null(a, true);
8336 b = must_be_not_null(b, true);
8337 r = must_be_not_null(r, true);
8338
8339 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8340 assert(a_start, "a array is null");
8341 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8342 assert(b_start, "b array is null");
8343 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8344 assert(r_start, "r array is null");
8345
8346 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8347 OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8348 stubAddr, stubName, TypePtr::BOTTOM,
8349 a_start, b_start, r_start);
8350 return true;
8351 }
8352
8353 bool LibraryCallKit::inline_intpoly_assign() {
8354 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8355 assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8356 const char *stubName = "intpoly_assign";
8357 address stubAddr = StubRoutines::intpoly_assign();
8358 if (!stubAddr) return false;
8359
8360 Node* set = argument(0);
8361 Node* a = argument(1);
8362 Node* b = argument(2);
8363 Node* arr_length = load_array_length(a);
8364
8365 a = must_be_not_null(a, true);
8366 b = must_be_not_null(b, true);
8367
8368 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8369 assert(a_start, "a array is null");
8370 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8371 assert(b_start, "b array is null");
8372
8373 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8374 OptoRuntime::intpoly_assign_Type(),
8375 stubAddr, stubName, TypePtr::BOTTOM,
8376 set, a_start, b_start, arr_length);
8377 return true;
8378 }
8379
8380 bool LibraryCallKit::inline_intpoly_mult_25519() {
8381 address stubAddr;
8382 const char *stubName;
8383 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
8384 assert(callee()->signature()->size() == 3, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
8385 stubAddr = StubRoutines::intpoly_mult_25519();
8386 stubName = "intpoly_mult_25519";
8387
8388 if (!stubAddr) return false;
8389 null_check_receiver(); // null-check receiver
8390 if (stopped()) return true;
8391
8392 Node* a = argument(1);
8393 Node* b = argument(2);
8394 Node* r = argument(3);
8395
8396 a = must_be_not_null(a, true);
8397 b = must_be_not_null(b, true);
8398 r = must_be_not_null(r, true);
8399
8400 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8401 assert(a_start, "a array is null");
8402 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8403 assert(b_start, "b array is null");
8404 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8405 assert(r_start, "r array is null");
8406
8407 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8408 OptoRuntime::intpoly_mult_25519_Type(),
8409 stubAddr, stubName, TypePtr::BOTTOM,
8410 a_start, b_start, r_start);
8411 return true;
8412 }
8413
8414 bool LibraryCallKit::inline_intpoly_square_25519() {
8415 address stubAddr;
8416 const char *stubName;
8417 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
8418 assert(callee()->signature()->size() == 2, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
8419 stubAddr = StubRoutines::intpoly_square_25519();
8420 stubName = "intpoly_square_25519";
8421
8422 if (!stubAddr) return false;
8423 null_check_receiver(); // null-check receiver
8424 if (stopped()) return true;
8425
8426 Node* a = argument(1);
8427 Node* r = argument(2);
8428
8429 a = must_be_not_null(a, true);
8430 r = must_be_not_null(r, true);
8431
8432 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8433 assert(a_start, "a array is null");
8434 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8435 assert(r_start, "r array is null");
8436
8437 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8438 OptoRuntime::intpoly_square_25519_Type(),
8439 stubAddr, stubName, TypePtr::BOTTOM,
8440 a_start, r_start);
8441 return true;
8442 }
8443
8444 //------------------------------inline_digestBase_implCompress-----------------------
8445 //
8446 // Calculate MD5 for single-block byte[] array.
8447 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8448 //
8449 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8450 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8451 //
8452 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8453 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8454 //
8455 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8456 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8457 //
8458 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8459 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8460 //
8461 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8462 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8463
8464 Node* digestBase_obj = argument(0);
8465 Node* src = argument(1); // type oop
8466 Node* ofs = argument(2); // type int
8467
8468 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8469 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8470 // failed array check
8471 return false;
8472 }
8473 // Figure out the size and type of the elements we will be copying.
8474 BasicType src_elem = src_type->elem()->array_element_basic_type();
8475 if (src_elem != T_BYTE) {
8476 return false;
8477 }
8478 // 'src_start' points to src array + offset
8479 src = must_be_not_null(src, true);
8480 Node* src_start = array_element_address(src, ofs, src_elem);
8481 Node* state = nullptr;
8482 Node* block_size = nullptr;
8483 address stubAddr;
8484 const char *stubName;
8485
8486 switch(id) {
8487 case vmIntrinsics::_md5_implCompress:
8488 assert(UseMD5Intrinsics, "need MD5 instruction support");
8489 state = get_state_from_digest_object(digestBase_obj, T_INT);
8490 stubAddr = StubRoutines::md5_implCompress();
8491 stubName = "md5_implCompress";
8492 break;
8493 case vmIntrinsics::_sha_implCompress:
8494 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8495 state = get_state_from_digest_object(digestBase_obj, T_INT);
8496 stubAddr = StubRoutines::sha1_implCompress();
8497 stubName = "sha1_implCompress";
8498 break;
8499 case vmIntrinsics::_sha2_implCompress:
8500 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8501 state = get_state_from_digest_object(digestBase_obj, T_INT);
8502 stubAddr = StubRoutines::sha256_implCompress();
8503 stubName = "sha256_implCompress";
8504 break;
8505 case vmIntrinsics::_sha5_implCompress:
8506 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8507 state = get_state_from_digest_object(digestBase_obj, T_LONG);
8508 stubAddr = StubRoutines::sha512_implCompress();
8509 stubName = "sha512_implCompress";
8510 break;
8511 case vmIntrinsics::_sha3_implCompress:
8512 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8513 state = get_state_from_digest_object(digestBase_obj, T_LONG);
8514 stubAddr = StubRoutines::sha3_implCompress();
8515 stubName = "sha3_implCompress";
8516 block_size = get_block_size_from_digest_object(digestBase_obj);
8517 if (block_size == nullptr) return false;
8518 break;
8519 default:
8520 fatal_unexpected_iid(id);
8521 return false;
8522 }
8523 if (state == nullptr) return false;
8524
8525 assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
8526 if (stubAddr == nullptr) return false;
8527
8528 // Call the stub.
8529 Node* call;
8530 if (block_size == nullptr) {
8531 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
8532 stubAddr, stubName, TypePtr::BOTTOM,
8533 src_start, state);
8534 } else {
8535 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
8536 stubAddr, stubName, TypePtr::BOTTOM,
8537 src_start, state, block_size);
8538 }
8539
8540 return true;
8541 }
8542
8543 //------------------------------inline_keccak
8544 bool LibraryCallKit::inline_keccak(vmIntrinsics::ID id) {
8545 address stubAddr = nullptr;
8546 const char *stubName;
8547 assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
8548 assert((id == vmIntrinsics::_double_keccak && callee()->signature()->size() == 2) ||
8549 (id == vmIntrinsics::_quad_keccak && callee()->signature()->size() == 4),
8550 "double_keccak wrong number of parameters");
8551
8552 int parmCnt = 0;
8553 switch (id) {
8554 case vmIntrinsics::_double_keccak:
8555 stubAddr = StubRoutines::double_keccak();
8556 stubName = "double_keccak";
8557 parmCnt = 2;
8558 break;
8559 case vmIntrinsics::_quad_keccak:
8560 stubAddr = StubRoutines::quad_keccak();
8561 stubName = "quad_keccak";
8562 parmCnt = 4;
8563 break;
8564 default:
8565 ShouldNotReachHere();
8566 }
8567
8568 if (!stubAddr) return false;
8569
8570 Node* state[4];
8571 for (int i = 0; i<parmCnt; i++) {
8572 state[i] = must_be_not_null(argument(i), true);
8573 state[i] = array_element_address(state[i], intcon(0), T_LONG);
8574 assert(state[i], "state[%d] is null", i);
8575 }
8576
8577 Node* keccak;
8578 switch (id) {
8579 case vmIntrinsics::_double_keccak:
8580 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8581 OptoRuntime::double_keccak_Type(),
8582 stubAddr, stubName, TypePtr::BOTTOM,
8583 state[0], state[1]);
8584 break;
8585 case vmIntrinsics::_quad_keccak:
8586 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8587 OptoRuntime::quad_keccak_Type(),
8588 stubAddr, stubName, TypePtr::BOTTOM,
8589 state[0], state[1], state[2], state[3]);
8590 break;
8591 default:
8592 ShouldNotReachHere();
8593 }
8594
8595 // return an int
8596 Node* retvalue = _gvn.transform(new ProjNode(keccak, TypeFunc::Parms));
8597 set_result(retvalue);
8598 return true;
8599 }
8600
8601
8602 //------------------------------inline_digestBase_implCompressMB-----------------------
8603 //
8604 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
8605 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
8606 //
8607 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
8608 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8609 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8610 assert((uint)predicate < 5, "sanity");
8611 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
8612
8613 Node* digestBase_obj = argument(0); // The receiver was checked for null already.
8614 Node* src = argument(1); // byte[] array
8615 Node* ofs = argument(2); // type int
8616 Node* limit = argument(3); // type int
8617
8618 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8619 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8620 // failed array check
8621 return false;
8622 }
8623 // Figure out the size and type of the elements we will be copying.
8624 BasicType src_elem = src_type->elem()->array_element_basic_type();
8625 if (src_elem != T_BYTE) {
8626 return false;
8627 }
8628 // 'src_start' points to src array + offset
8629 src = must_be_not_null(src, false);
8630 Node* src_start = array_element_address(src, ofs, src_elem);
8631
8632 const char* klass_digestBase_name = nullptr;
8633 const char* stub_name = nullptr;
8634 address stub_addr = nullptr;
8635 BasicType elem_type = T_INT;
8636
8637 switch (predicate) {
8638 case 0:
8639 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
8640 klass_digestBase_name = "sun/security/provider/MD5";
8641 stub_name = "md5_implCompressMB";
8642 stub_addr = StubRoutines::md5_implCompressMB();
8643 }
8644 break;
8645 case 1:
8646 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
8647 klass_digestBase_name = "sun/security/provider/SHA";
8648 stub_name = "sha1_implCompressMB";
8649 stub_addr = StubRoutines::sha1_implCompressMB();
8650 }
8651 break;
8652 case 2:
8653 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
8654 klass_digestBase_name = "sun/security/provider/SHA2";
8655 stub_name = "sha256_implCompressMB";
8656 stub_addr = StubRoutines::sha256_implCompressMB();
8657 }
8658 break;
8659 case 3:
8660 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
8661 klass_digestBase_name = "sun/security/provider/SHA5";
8662 stub_name = "sha512_implCompressMB";
8663 stub_addr = StubRoutines::sha512_implCompressMB();
8664 elem_type = T_LONG;
8665 }
8666 break;
8667 case 4:
8668 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
8669 klass_digestBase_name = "sun/security/provider/SHA3";
8670 stub_name = "sha3_implCompressMB";
8671 stub_addr = StubRoutines::sha3_implCompressMB();
8672 elem_type = T_LONG;
8673 }
8674 break;
8675 default:
8676 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
8677 }
8678 if (klass_digestBase_name != nullptr) {
8679 assert(stub_addr != nullptr, "Stub is generated");
8680 if (stub_addr == nullptr) return false;
8681
8682 // get DigestBase klass to lookup for SHA klass
8683 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
8684 assert(tinst != nullptr, "digestBase_obj is not instance???");
8685 assert(tinst->is_loaded(), "DigestBase is not loaded");
8686
8687 ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
8688 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
8689 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
8690 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
8691 }
8692 return false;
8693 }
8694
8695 //------------------------------inline_digestBase_implCompressMB-----------------------
8696 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
8697 BasicType elem_type, address stubAddr, const char *stubName,
8698 Node* src_start, Node* ofs, Node* limit) {
8699 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
8700 const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8701 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
8702 digest_obj = _gvn.transform(digest_obj);
8703
8704 Node* state = get_state_from_digest_object(digest_obj, elem_type);
8705 if (state == nullptr) return false;
8706
8707 Node* block_size = nullptr;
8708 if (strcmp("sha3_implCompressMB", stubName) == 0) {
8709 block_size = get_block_size_from_digest_object(digest_obj);
8710 if (block_size == nullptr) return false;
8711 }
8712
8713 // Call the stub.
8714 Node* call;
8715 if (block_size == nullptr) {
8716 call = make_runtime_call(RC_LEAF|RC_NO_FP,
8717 OptoRuntime::digestBase_implCompressMB_Type(false),
8718 stubAddr, stubName, TypePtr::BOTTOM,
8719 src_start, state, ofs, limit);
8720 } else {
8721 call = make_runtime_call(RC_LEAF|RC_NO_FP,
8722 OptoRuntime::digestBase_implCompressMB_Type(true),
8723 stubAddr, stubName, TypePtr::BOTTOM,
8724 src_start, state, block_size, ofs, limit);
8725 }
8726
8727 // return ofs (int)
8728 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8729 set_result(result);
8730
8731 return true;
8732 }
8733
8734 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
8735 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
8736 assert(UseAES, "need AES instruction support");
8737 address stubAddr = nullptr;
8738 const char *stubName = nullptr;
8739 stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
8740 stubName = "galoisCounterMode_AESCrypt";
8741
8742 if (stubAddr == nullptr) return false;
8743
8744 Node* in = argument(0);
8745 Node* inOfs = argument(1);
8746 Node* len = argument(2);
8747 Node* ct = argument(3);
8748 Node* ctOfs = argument(4);
8749 Node* out = argument(5);
8750 Node* outOfs = argument(6);
8751 Node* gctr_object = argument(7);
8752 Node* ghash_object = argument(8);
8753
8754 // (1) in, ct and out are arrays.
8755 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
8756 const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
8757 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
8758 assert( in_type != nullptr && in_type->elem() != Type::BOTTOM &&
8759 ct_type != nullptr && ct_type->elem() != Type::BOTTOM &&
8760 out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
8761
8762 // checks are the responsibility of the caller
8763 Node* in_start = in;
8764 Node* ct_start = ct;
8765 Node* out_start = out;
8766 if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
8767 assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
8768 in_start = array_element_address(in, inOfs, T_BYTE);
8769 ct_start = array_element_address(ct, ctOfs, T_BYTE);
8770 out_start = array_element_address(out, outOfs, T_BYTE);
8771 }
8772
8773 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8774 // (because of the predicated logic executed earlier).
8775 // so we cast it here safely.
8776 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8777 Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8778 Node* counter = load_field_from_object(gctr_object, "counter", "[B");
8779 Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
8780 Node* state = load_field_from_object(ghash_object, "state", "[J");
8781
8782 if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
8783 return false;
8784 }
8785 // cast it to what we know it will be at runtime
8786 const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
8787 assert(tinst != nullptr, "GCTR obj is null");
8788 assert(tinst->is_loaded(), "GCTR obj is not loaded");
8789 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8790 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8791 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8792 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8793 const TypeOopPtr* xtype = aklass->as_instance_type();
8794 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8795 aescrypt_object = _gvn.transform(aescrypt_object);
8796 // we need to get the start of the aescrypt_object's expanded key array
8797 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8798 if (k_start == nullptr) return false;
8799 // similarly, get the start address of the r vector
8800 Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
8801 Node* state_start = array_element_address(state, intcon(0), T_LONG);
8802 Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
8803
8804
8805 // Call the stub, passing params
8806 Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8807 OptoRuntime::galoisCounterMode_aescrypt_Type(),
8808 stubAddr, stubName, TypePtr::BOTTOM,
8809 in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
8810
8811 // return cipher length (int)
8812 Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
8813 set_result(retvalue);
8814
8815 return true;
8816 }
8817
8818 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
8819 // Return node representing slow path of predicate check.
8820 // the pseudo code we want to emulate with this predicate is:
8821 // for encryption:
8822 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8823 // for decryption:
8824 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8825 // note cipher==plain is more conservative than the original java code but that's OK
8826 //
8827
8828 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
8829 // The receiver was checked for null already.
8830 Node* objGCTR = argument(7);
8831 // Load embeddedCipher field of GCTR object.
8832 Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8833 assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
8834
8835 // get AESCrypt klass for instanceOf check
8836 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8837 // will have same classloader as CipherBlockChaining object
8838 const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
8839 assert(tinst != nullptr, "GCTR obj is null");
8840 assert(tinst->is_loaded(), "GCTR obj is not loaded");
8841
8842 // we want to do an instanceof comparison against the AESCrypt class
8843 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8844 if (!klass_AESCrypt->is_loaded()) {
8845 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8846 Node* ctrl = control();
8847 set_control(top()); // no regular fast path
8848 return ctrl;
8849 }
8850
8851 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8852 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8853 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8854 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8855 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8856
8857 return instof_false; // even if it is null
8858 }
8859
8860 //------------------------------get_state_from_digest_object-----------------------
8861 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
8862 const char* state_type;
8863 switch (elem_type) {
8864 case T_BYTE: state_type = "[B"; break;
8865 case T_INT: state_type = "[I"; break;
8866 case T_LONG: state_type = "[J"; break;
8867 default: ShouldNotReachHere();
8868 }
8869 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
8870 assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
8871 if (digest_state == nullptr) return (Node *) nullptr;
8872
8873 // now have the array, need to get the start address of the state array
8874 Node* state = array_element_address(digest_state, intcon(0), elem_type);
8875 return state;
8876 }
8877
8878 //------------------------------get_block_size_from_sha3_object----------------------------------
8879 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
8880 Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
8881 assert (block_size != nullptr, "sanity");
8882 return block_size;
8883 }
8884
8885 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
8886 // Return node representing slow path of predicate check.
8887 // the pseudo code we want to emulate with this predicate is:
8888 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
8889 //
8890 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
8891 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8892 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8893 assert((uint)predicate < 5, "sanity");
8894
8895 // The receiver was checked for null already.
8896 Node* digestBaseObj = argument(0);
8897
8898 // get DigestBase klass for instanceOf check
8899 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
8900 assert(tinst != nullptr, "digestBaseObj is null");
8901 assert(tinst->is_loaded(), "DigestBase is not loaded");
8902
8903 const char* klass_name = nullptr;
8904 switch (predicate) {
8905 case 0:
8906 if (UseMD5Intrinsics) {
8907 // we want to do an instanceof comparison against the MD5 class
8908 klass_name = "sun/security/provider/MD5";
8909 }
8910 break;
8911 case 1:
8912 if (UseSHA1Intrinsics) {
8913 // we want to do an instanceof comparison against the SHA class
8914 klass_name = "sun/security/provider/SHA";
8915 }
8916 break;
8917 case 2:
8918 if (UseSHA256Intrinsics) {
8919 // we want to do an instanceof comparison against the SHA2 class
8920 klass_name = "sun/security/provider/SHA2";
8921 }
8922 break;
8923 case 3:
8924 if (UseSHA512Intrinsics) {
8925 // we want to do an instanceof comparison against the SHA5 class
8926 klass_name = "sun/security/provider/SHA5";
8927 }
8928 break;
8929 case 4:
8930 if (UseSHA3Intrinsics) {
8931 // we want to do an instanceof comparison against the SHA3 class
8932 klass_name = "sun/security/provider/SHA3";
8933 }
8934 break;
8935 default:
8936 fatal("unknown SHA intrinsic predicate: %d", predicate);
8937 }
8938
8939 ciKlass* klass = nullptr;
8940 if (klass_name != nullptr) {
8941 klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
8942 }
8943 if ((klass == nullptr) || !klass->is_loaded()) {
8944 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
8945 Node* ctrl = control();
8946 set_control(top()); // no intrinsic path
8947 return ctrl;
8948 }
8949 ciInstanceKlass* instklass = klass->as_instance_klass();
8950
8951 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
8952 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8953 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8954 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8955
8956 return instof_false; // even if it is null
8957 }
8958
8959 //-------------inline_fma-----------------------------------
8960 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
8961 Node *a = nullptr;
8962 Node *b = nullptr;
8963 Node *c = nullptr;
8964 Node* result = nullptr;
8965 switch (id) {
8966 case vmIntrinsics::_fmaD:
8967 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
8968 // no receiver since it is static method
8969 a = argument(0);
8970 b = argument(2);
8971 c = argument(4);
8972 result = _gvn.transform(new FmaDNode(a, b, c));
8973 break;
8974 case vmIntrinsics::_fmaF:
8975 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
8976 a = argument(0);
8977 b = argument(1);
8978 c = argument(2);
8979 result = _gvn.transform(new FmaFNode(a, b, c));
8980 break;
8981 default:
8982 fatal_unexpected_iid(id); break;
8983 }
8984 set_result(result);
8985 return true;
8986 }
8987
8988 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
8989 // argument(0) is receiver
8990 Node* codePoint = argument(1);
8991 Node* n = nullptr;
8992
8993 switch (id) {
8994 case vmIntrinsics::_isDigit :
8995 n = new DigitNode(control(), codePoint);
8996 break;
8997 case vmIntrinsics::_isLowerCase :
8998 n = new LowerCaseNode(control(), codePoint);
8999 break;
9000 case vmIntrinsics::_isUpperCase :
9001 n = new UpperCaseNode(control(), codePoint);
9002 break;
9003 case vmIntrinsics::_isWhitespace :
9004 n = new WhitespaceNode(control(), codePoint);
9005 break;
9006 default:
9007 fatal_unexpected_iid(id);
9008 }
9009
9010 set_result(_gvn.transform(n));
9011 return true;
9012 }
9013
9014 bool LibraryCallKit::inline_profileBoolean() {
9015 Node* counts = argument(1);
9016 const TypeAryPtr* ary = nullptr;
9017 ciArray* aobj = nullptr;
9018 if (counts->is_Con()
9019 && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9020 && (aobj = ary->const_oop()->as_array()) != nullptr
9021 && (aobj->length() == 2)) {
9022 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9023 jint false_cnt = aobj->element_value(0).as_int();
9024 jint true_cnt = aobj->element_value(1).as_int();
9025
9026 if (C->log() != nullptr) {
9027 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9028 false_cnt, true_cnt);
9029 }
9030
9031 if (false_cnt + true_cnt == 0) {
9032 // According to profile, never executed.
9033 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9034 Deoptimization::Action_reinterpret);
9035 return true;
9036 }
9037
9038 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9039 // is a number of each value occurrences.
9040 Node* result = argument(0);
9041 if (false_cnt == 0 || true_cnt == 0) {
9042 // According to profile, one value has been never seen.
9043 int expected_val = (false_cnt == 0) ? 1 : 0;
9044
9045 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9046 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9047
9048 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9049 Node* fast_path = _gvn.transform(new IfTrueNode(check));
9050 Node* slow_path = _gvn.transform(new IfFalseNode(check));
9051
9052 { // Slow path: uncommon trap for never seen value and then reexecute
9053 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9054 // the value has been seen at least once.
9055 PreserveJVMState pjvms(this);
9056 PreserveReexecuteState preexecs(this);
9057 jvms()->set_should_reexecute(true);
9058
9059 set_control(slow_path);
9060 set_i_o(i_o());
9061
9062 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9063 Deoptimization::Action_reinterpret);
9064 }
9065 // The guard for never seen value enables sharpening of the result and
9066 // returning a constant. It allows to eliminate branches on the same value
9067 // later on.
9068 set_control(fast_path);
9069 result = intcon(expected_val);
9070 }
9071 // Stop profiling.
9072 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9073 // By replacing method body with profile data (represented as ProfileBooleanNode
9074 // on IR level) we effectively disable profiling.
9075 // It enables full speed execution once optimized code is generated.
9076 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9077 C->record_for_igvn(profile);
9078 set_result(profile);
9079 return true;
9080 } else {
9081 // Continue profiling.
9082 // Profile data isn't available at the moment. So, execute method's bytecode version.
9083 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9084 // is compiled and counters aren't available since corresponding MethodHandle
9085 // isn't a compile-time constant.
9086 return false;
9087 }
9088 }
9089
9090 bool LibraryCallKit::inline_isCompileConstant() {
9091 Node* n = argument(0);
9092 set_result(n->is_Con() ? intcon(1) : intcon(0));
9093 return true;
9094 }
9095
9096 //------------------------------- inline_getObjectSize --------------------------------------
9097 //
9098 // Calculate the runtime size of the object/array.
9099 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9100 //
9101 bool LibraryCallKit::inline_getObjectSize() {
9102 Node* obj = argument(3);
9103 Node* klass_node = load_object_klass(obj);
9104
9105 jint layout_con = Klass::_lh_neutral_value;
9106 Node* layout_val = get_layout_helper(klass_node, layout_con);
9107 int layout_is_con = (layout_val == nullptr);
9108
9109 if (layout_is_con) {
9110 // Layout helper is constant, can figure out things at compile time.
9111
9112 if (Klass::layout_helper_is_instance(layout_con)) {
9113 // Instance case: layout_con contains the size itself.
9114 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9115 set_result(size);
9116 } else {
9117 // Array case: size is round(header + element_size*arraylength).
9118 // Since arraylength is different for every array instance, we have to
9119 // compute the whole thing at runtime.
9120
9121 Node* arr_length = load_array_length(obj);
9122
9123 int round_mask = MinObjAlignmentInBytes - 1;
9124 int hsize = Klass::layout_helper_header_size(layout_con);
9125 int eshift = Klass::layout_helper_log2_element_size(layout_con);
9126
9127 if ((round_mask & ~right_n_bits(eshift)) == 0) {
9128 round_mask = 0; // strength-reduce it if it goes away completely
9129 }
9130 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9131 Node* header_size = intcon(hsize + round_mask);
9132
9133 Node* lengthx = ConvI2X(arr_length);
9134 Node* headerx = ConvI2X(header_size);
9135
9136 Node* abody = lengthx;
9137 if (eshift != 0) {
9138 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9139 }
9140 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9141 if (round_mask != 0) {
9142 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9143 }
9144 size = ConvX2L(size);
9145 set_result(size);
9146 }
9147 } else {
9148 // Layout helper is not constant, need to test for array-ness at runtime.
9149
9150 enum { _instance_path = 1, _array_path, PATH_LIMIT };
9151 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9152 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9153 record_for_igvn(result_reg);
9154
9155 Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9156 if (array_ctl != nullptr) {
9157 // Array case: size is round(header + element_size*arraylength).
9158 // Since arraylength is different for every array instance, we have to
9159 // compute the whole thing at runtime.
9160
9161 PreserveJVMState pjvms(this);
9162 set_control(array_ctl);
9163 Node* arr_length = load_array_length(obj);
9164
9165 int round_mask = MinObjAlignmentInBytes - 1;
9166 Node* mask = intcon(round_mask);
9167
9168 Node* hss = intcon(Klass::_lh_header_size_shift);
9169 Node* hsm = intcon(Klass::_lh_header_size_mask);
9170 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9171 header_size = _gvn.transform(new AndINode(header_size, hsm));
9172 header_size = _gvn.transform(new AddINode(header_size, mask));
9173
9174 // There is no need to mask or shift this value.
9175 // The semantics of LShiftINode include an implicit mask to 0x1F.
9176 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9177 Node* elem_shift = layout_val;
9178
9179 Node* lengthx = ConvI2X(arr_length);
9180 Node* headerx = ConvI2X(header_size);
9181
9182 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9183 Node* size = _gvn.transform(new AddXNode(headerx, abody));
9184 if (round_mask != 0) {
9185 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9186 }
9187 size = ConvX2L(size);
9188
9189 result_reg->init_req(_array_path, control());
9190 result_val->init_req(_array_path, size);
9191 }
9192
9193 if (!stopped()) {
9194 // Instance case: the layout helper gives us instance size almost directly,
9195 // but we need to mask out the _lh_instance_slow_path_bit.
9196 Node* size = ConvI2X(layout_val);
9197 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9198 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9199 size = _gvn.transform(new AndXNode(size, mask));
9200 size = ConvX2L(size);
9201
9202 result_reg->init_req(_instance_path, control());
9203 result_val->init_req(_instance_path, size);
9204 }
9205
9206 set_result(result_reg, result_val);
9207 }
9208
9209 return true;
9210 }
9211
9212 //------------------------------- inline_blackhole --------------------------------------
9213 //
9214 // Make sure all arguments to this node are alive.
9215 // This matches methods that were requested to be blackholed through compile commands.
9216 //
9217 bool LibraryCallKit::inline_blackhole() {
9218 assert(callee()->is_static(), "Should have been checked before: only static methods here");
9219 assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9220 assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9221
9222 // Blackhole node pinches only the control, not memory. This allows
9223 // the blackhole to be pinned in the loop that computes blackholed
9224 // values, but have no other side effects, like breaking the optimizations
9225 // across the blackhole.
9226
9227 Node* bh = _gvn.transform(new BlackholeNode(control()));
9228 set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9229
9230 // Bind call arguments as blackhole arguments to keep them alive
9231 uint nargs = callee()->arg_size();
9232 for (uint i = 0; i < nargs; i++) {
9233 bh->add_req(argument(i));
9234 }
9235
9236 return true;
9237 }
9238
9239 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9240 const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9241 if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9242 return nullptr; // box klass is not Float16
9243 }
9244
9245 // Null check; get notnull casted pointer
9246 Node* null_ctl = top();
9247 Node* not_null_box = null_check_oop(box, &null_ctl, true);
9248 // If not_null_box is dead, only null-path is taken
9249 if (stopped()) {
9250 set_control(null_ctl);
9251 return nullptr;
9252 }
9253 assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9254 const TypePtr* adr_type = C->alias_type(field)->adr_type();
9255 Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9256 return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9257 }
9258
9259 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9260 PreserveReexecuteState preexecs(this);
9261 jvms()->set_should_reexecute(true);
9262
9263 const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9264 Node* klass_node = makecon(klass_type);
9265 Node* box = new_instance(klass_node);
9266
9267 Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9268 const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9269
9270 Node* field_store = _gvn.transform(access_store_at(box,
9271 value_field,
9272 value_adr_type,
9273 value,
9274 TypeInt::SHORT,
9275 T_SHORT,
9276 IN_HEAP));
9277 set_memory(field_store, value_adr_type);
9278 return box;
9279 }
9280
9281 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9282 if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9283 !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9284 return false;
9285 }
9286
9287 const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9288 if (box_type == nullptr || box_type->const_oop() == nullptr) {
9289 return false;
9290 }
9291
9292 ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9293 const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9294 ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9295 ciSymbols::short_signature(),
9296 false);
9297 assert(field != nullptr, "");
9298
9299 // Transformed nodes
9300 Node* fld1 = nullptr;
9301 Node* fld2 = nullptr;
9302 Node* fld3 = nullptr;
9303 switch(num_args) {
9304 case 3:
9305 fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9306 if (fld3 == nullptr) {
9307 return false;
9308 }
9309 fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9310 // fall-through
9311 case 2:
9312 fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9313 if (fld2 == nullptr) {
9314 return false;
9315 }
9316 fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9317 // fall-through
9318 case 1:
9319 fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9320 if (fld1 == nullptr) {
9321 return false;
9322 }
9323 fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9324 break;
9325 default: fatal("Unsupported number of arguments %d", num_args);
9326 }
9327
9328 Node* result = nullptr;
9329 switch (id) {
9330 // Unary operations
9331 case vmIntrinsics::_sqrt_float16:
9332 result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9333 break;
9334 // Ternary operations
9335 case vmIntrinsics::_fma_float16:
9336 result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9337 break;
9338 default:
9339 fatal_unexpected_iid(id);
9340 break;
9341 }
9342 result = _gvn.transform(new ReinterpretHF2SNode(result));
9343 set_result(box_fp16_value(float16_box_type, field, result));
9344 return true;
9345 }
9346