1 /*
2 * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 #include "classfile/classLoaderData.inline.hpp"
25 #include "classfile/javaClasses.inline.hpp"
26 #include "classfile/stringTable.hpp"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmClasses.hpp"
30 #include "code/scopeDesc.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "compiler/compilerEvent.hpp"
33 #include "compiler/compilerOracle.hpp"
34 #include "compiler/disassembler.hpp"
35 #include "compiler/oopMap.hpp"
36 #include "interpreter/bytecodeStream.hpp"
37 #include "interpreter/linkResolver.hpp"
38 #include "interpreter/oopMapCache.hpp"
39 #include "jfr/jfrEvents.hpp"
40 #include "jvmci/jvmciCodeInstaller.hpp"
41 #include "jvmci/jvmciCompilerToVM.hpp"
42 #include "jvmci/jvmciRuntime.hpp"
43 #include "logging/log.hpp"
44 #include "logging/logTag.hpp"
45 #include "memory/oopFactory.hpp"
46 #include "memory/universe.hpp"
47 #include "oops/constantPool.inline.hpp"
48 #include "oops/instanceKlass.inline.hpp"
49 #include "oops/instanceMirrorKlass.hpp"
50 #include "oops/method.inline.hpp"
51 #include "oops/objArrayKlass.inline.hpp"
52 #include "oops/typeArrayOop.inline.hpp"
53 #include "prims/jvmtiExport.hpp"
54 #include "prims/methodHandles.hpp"
55 #include "prims/nativeLookup.hpp"
56 #include "runtime/arguments.hpp"
57 #include "runtime/atomic.hpp"
58 #include "runtime/deoptimization.hpp"
59 #include "runtime/fieldDescriptor.inline.hpp"
60 #include "runtime/frame.inline.hpp"
61 #include "runtime/globals_extension.hpp"
62 #include "runtime/interfaceSupport.inline.hpp"
63 #include "runtime/jniHandles.inline.hpp"
64 #include "runtime/keepStackGCProcessed.hpp"
65 #include "runtime/reflection.hpp"
66 #include "runtime/stackFrameStream.inline.hpp"
67 #include "runtime/timerTrace.hpp"
68 #include "runtime/vframe.inline.hpp"
69 #include "runtime/vframe_hp.hpp"
70 #if INCLUDE_JFR
71 #include "jfr/jfr.hpp"
72 #endif
73
74 JVMCIKlassHandle::JVMCIKlassHandle(Thread* thread, Klass* klass) {
75 _thread = thread;
76 _klass = klass;
77 if (klass != nullptr) {
78 _holder = Handle(_thread, klass->klass_holder());
79 }
80 }
81
82 JVMCIKlassHandle& JVMCIKlassHandle::operator=(Klass* klass) {
83 _klass = klass;
84 if (klass != nullptr) {
85 _holder = Handle(_thread, klass->klass_holder());
86 }
87 return *this;
88 }
89
90 static void requireInHotSpot(const char* caller, JVMCI_TRAPS) {
91 if (!JVMCIENV->is_hotspot()) {
92 JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from JVMCI shared library", caller));
93 }
94 }
95
96 static void requireNotInHotSpot(const char* caller, JVMCI_TRAPS) {
97 if (JVMCIENV->is_hotspot()) {
98 JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from HotSpot", caller));
99 }
100 }
101
102 class JVMCITraceMark : public StackObj {
103 const char* _msg;
104 public:
105 JVMCITraceMark(const char* msg) {
106 _msg = msg;
107 JVMCI_event_2("Enter %s", _msg);
108 }
109 ~JVMCITraceMark() {
110 JVMCI_event_2(" Exit %s", _msg);
111 }
112 };
113
114 class JavaArgumentUnboxer : public SignatureIterator {
115 protected:
116 JavaCallArguments* _jca;
117 arrayOop _args;
118 int _index;
119
120 Handle next_arg(BasicType expectedType);
121
122 public:
123 JavaArgumentUnboxer(Symbol* signature,
124 JavaCallArguments* jca,
125 arrayOop args,
126 bool is_static)
127 : SignatureIterator(signature)
128 {
129 this->_return_type = T_ILLEGAL;
130 _jca = jca;
131 _index = 0;
132 _args = args;
133 if (!is_static) {
134 _jca->push_oop(next_arg(T_OBJECT));
135 }
136 do_parameters_on(this);
137 assert(_index == args->length(), "arg count mismatch with signature");
138 }
139
140 private:
141 friend class SignatureIterator; // so do_parameters_on can call do_type
142 void do_type(BasicType type) {
143 if (is_reference_type(type)) {
144 _jca->push_oop(next_arg(T_OBJECT));
145 return;
146 }
147 Handle arg = next_arg(type);
148 int box_offset = java_lang_boxing_object::value_offset(type);
149 switch (type) {
150 case T_BOOLEAN: _jca->push_int(arg->bool_field(box_offset)); break;
151 case T_CHAR: _jca->push_int(arg->char_field(box_offset)); break;
152 case T_SHORT: _jca->push_int(arg->short_field(box_offset)); break;
153 case T_BYTE: _jca->push_int(arg->byte_field(box_offset)); break;
154 case T_INT: _jca->push_int(arg->int_field(box_offset)); break;
155 case T_LONG: _jca->push_long(arg->long_field(box_offset)); break;
156 case T_FLOAT: _jca->push_float(arg->float_field(box_offset)); break;
157 case T_DOUBLE: _jca->push_double(arg->double_field(box_offset)); break;
158 default: ShouldNotReachHere();
159 }
160 }
161 };
162
163 Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
164 assert(_index < _args->length(), "out of bounds");
165 oop arg=((objArrayOop) (_args))->obj_at(_index++);
166 assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
167 return Handle(Thread::current(), arg);
168 }
169
170 // Bring the JVMCI compiler thread into the VM state.
171 #define JVMCI_VM_ENTRY_MARK \
172 MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread)); \
173 ThreadInVMfromNative __tiv(thread); \
174 HandleMarkCleaner __hm(thread); \
175 JavaThread* THREAD = thread; \
176 DEBUG_ONLY(VMNativeEntryWrapper __vew;)
177
178 // Native method block that transitions current thread to '_thread_in_vm'.
179 // Note: CompilerThreadCanCallJava must precede JVMCIENV_FROM_JNI so that
180 // the translation of an uncaught exception in the JVMCIEnv does not make
181 // a Java call when __is_hotspot == false.
182 #define C2V_BLOCK(result_type, name, signature) \
183 JVMCI_VM_ENTRY_MARK; \
184 ResourceMark rm; \
185 bool __is_hotspot = env == thread->jni_environment(); \
186 bool __block_can_call_java = __is_hotspot || !thread->is_Compiler_thread() || CompilerThread::cast(thread)->can_call_java(); \
187 CompilerThreadCanCallJava ccj(thread, __block_can_call_java); \
188 JVMCIENV_FROM_JNI(JVMCI::compilation_tick(thread), env); \
189
190 // Entry to native method implementation that transitions
191 // current thread to '_thread_in_vm'.
192 #define C2V_VMENTRY(result_type, name, signature) \
193 result_type JNICALL c2v_ ## name signature { \
194 JavaThread* thread = JavaThread::current_or_null(); \
195 if (thread == nullptr) { \
196 env->ThrowNew(JNIJVMCI::InternalError::clazz(), \
197 err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
198 return; \
199 } \
200 C2V_BLOCK(result_type, name, signature) \
201 JVMCITraceMark jtm("CompilerToVM::" #name);
202
203 #define C2V_VMENTRY_(result_type, name, signature, result) \
204 result_type JNICALL c2v_ ## name signature { \
205 JavaThread* thread = JavaThread::current_or_null(); \
206 if (thread == nullptr) { \
207 env->ThrowNew(JNIJVMCI::InternalError::clazz(), \
208 err_msg("Cannot call into HotSpot from JVMCI shared library without attaching current thread")); \
209 return result; \
210 } \
211 C2V_BLOCK(result_type, name, signature) \
212 JVMCITraceMark jtm("CompilerToVM::" #name);
213
214 #define C2V_VMENTRY_NULL(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, nullptr)
215 #define C2V_VMENTRY_0(result_type, name, signature) C2V_VMENTRY_(result_type, name, signature, 0)
216
217 // Entry to native method implementation that does not transition
218 // current thread to '_thread_in_vm'.
219 #define C2V_VMENTRY_PREFIX(result_type, name, signature) \
220 result_type JNICALL c2v_ ## name signature { \
221 JavaThread* thread = JavaThread::current_or_null();
222
223 #define C2V_END }
224
225 #define JNI_THROW(caller, name, msg) do { \
226 jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg); \
227 if (__throw_res != JNI_OK) { \
228 JVMCI_event_1("Throwing " #name " in " caller " returned %d", __throw_res); \
229 } \
230 return; \
231 } while (0);
232
233 #define JNI_THROW_(caller, name, msg, result) do { \
234 jint __throw_res = env->ThrowNew(JNIJVMCI::name::clazz(), msg); \
235 if (__throw_res != JNI_OK) { \
236 JVMCI_event_1("Throwing " #name " in " caller " returned %d", __throw_res); \
237 } \
238 return result; \
239 } while (0)
240
241 jobjectArray readConfiguration0(JNIEnv *env, JVMCI_TRAPS);
242
243 C2V_VMENTRY_NULL(jobjectArray, readConfiguration, (JNIEnv* env))
244 jobjectArray config = readConfiguration0(env, JVMCI_CHECK_NULL);
245 return config;
246 }
247
248 C2V_VMENTRY_NULL(jobject, getFlagValue, (JNIEnv* env, jobject c2vm, jobject name_handle))
249 #define RETURN_BOXED_LONG(value) jvalue p; p.j = (jlong) (value); JVMCIObject box = JVMCIENV->create_box(T_LONG, &p, JVMCI_CHECK_NULL); return box.as_jobject();
250 #define RETURN_BOXED_DOUBLE(value) jvalue p; p.d = (jdouble) (value); JVMCIObject box = JVMCIENV->create_box(T_DOUBLE, &p, JVMCI_CHECK_NULL); return box.as_jobject();
251 JVMCIObject name = JVMCIENV->wrap(name_handle);
252 if (name.is_null()) {
253 JVMCI_THROW_NULL(NullPointerException);
254 }
255 const char* cstring = JVMCIENV->as_utf8_string(name);
256 const JVMFlag* flag = JVMFlag::find_declared_flag(cstring);
257 if (flag == nullptr) {
258 return c2vm;
259 }
260 if (flag->is_bool()) {
261 jvalue prim;
262 prim.z = flag->get_bool();
263 JVMCIObject box = JVMCIENV->create_box(T_BOOLEAN, &prim, JVMCI_CHECK_NULL);
264 return JVMCIENV->get_jobject(box);
265 } else if (flag->is_ccstr()) {
266 JVMCIObject value = JVMCIENV->create_string(flag->get_ccstr(), JVMCI_CHECK_NULL);
267 return JVMCIENV->get_jobject(value);
268 } else if (flag->is_intx()) {
269 RETURN_BOXED_LONG(flag->get_intx());
270 } else if (flag->is_int()) {
271 RETURN_BOXED_LONG(flag->get_int());
272 } else if (flag->is_uint()) {
273 RETURN_BOXED_LONG(flag->get_uint());
274 } else if (flag->is_uint64_t()) {
275 RETURN_BOXED_LONG(flag->get_uint64_t());
276 } else if (flag->is_size_t()) {
277 RETURN_BOXED_LONG(flag->get_size_t());
278 } else if (flag->is_uintx()) {
279 RETURN_BOXED_LONG(flag->get_uintx());
280 } else if (flag->is_double()) {
281 RETURN_BOXED_DOUBLE(flag->get_double());
282 } else {
283 JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->name(), flag->type_string());
284 }
285 #undef RETURN_BOXED_LONG
286 #undef RETURN_BOXED_DOUBLE
287 C2V_END
288
289 // Macros for argument pairs representing a wrapper object and its wrapped VM pointer
290 #define ARGUMENT_PAIR(name) jobject name ## _obj, jlong name ## _pointer
291 #define UNPACK_PAIR(type, name) ((type*) name ## _pointer)
292
293 C2V_VMENTRY_NULL(jbyteArray, getBytecode, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
294 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
295
296 int code_size = method->code_size();
297 jbyte* reconstituted_code = NEW_RESOURCE_ARRAY(jbyte, code_size);
298
299 guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
300 // iterate over all bytecodes and replace non-Java bytecodes
301
302 for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
303 Bytecodes::Code code = s.code();
304 Bytecodes::Code raw_code = s.raw_code();
305 int bci = s.bci();
306 int len = s.instruction_size();
307
308 // Restore original byte code.
309 reconstituted_code[bci] = (jbyte) (s.is_wide()? Bytecodes::_wide : code);
310 if (len > 1) {
311 memcpy(reconstituted_code + (bci + 1), s.bcp()+1, len-1);
312 }
313
314 if (len > 1) {
315 // Restore the big-endian constant pool indexes.
316 // Cf. Rewriter::scan_method
317 switch (code) {
318 case Bytecodes::_getstatic:
319 case Bytecodes::_putstatic:
320 case Bytecodes::_getfield:
321 case Bytecodes::_putfield:
322 case Bytecodes::_invokevirtual:
323 case Bytecodes::_invokespecial:
324 case Bytecodes::_invokestatic:
325 case Bytecodes::_invokeinterface:
326 case Bytecodes::_invokehandle: {
327 int cp_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
328 Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
329 break;
330 }
331
332 case Bytecodes::_invokedynamic: {
333 int cp_index = Bytes::get_native_u4((address) reconstituted_code + (bci + 1));
334 Bytes::put_Java_u4((address) reconstituted_code + (bci + 1), (u4) cp_index);
335 break;
336 }
337
338 default:
339 break;
340 }
341
342 // Not all ldc byte code are rewritten.
343 switch (raw_code) {
344 case Bytecodes::_fast_aldc: {
345 int cpc_index = reconstituted_code[bci + 1] & 0xff;
346 int cp_index = method->constants()->object_to_cp_index(cpc_index);
347 assert(cp_index < method->constants()->length(), "sanity check");
348 reconstituted_code[bci + 1] = (jbyte) cp_index;
349 break;
350 }
351
352 case Bytecodes::_fast_aldc_w: {
353 int cpc_index = Bytes::get_native_u2((address) reconstituted_code + (bci + 1));
354 int cp_index = method->constants()->object_to_cp_index(cpc_index);
355 assert(cp_index < method->constants()->length(), "sanity check");
356 Bytes::put_Java_u2((address) reconstituted_code + (bci + 1), (u2) cp_index);
357 break;
358 }
359
360 default:
361 break;
362 }
363 }
364 }
365
366 JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
367 JVMCIENV->copy_bytes_from(reconstituted_code, result, 0, code_size);
368 return JVMCIENV->get_jbyteArray(result);
369 C2V_END
370
371 C2V_VMENTRY_0(jint, getExceptionTableLength, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
372 Method* method = UNPACK_PAIR(Method, method);
373 return method->exception_table_length();
374 C2V_END
375
376 C2V_VMENTRY_0(jlong, getExceptionTableStart, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
377 Method* method = UNPACK_PAIR(Method, method);
378 if (method->exception_table_length() == 0) {
379 return 0L;
380 }
381 return (jlong) (address) method->exception_table_start();
382 C2V_END
383
384 C2V_VMENTRY_NULL(jobject, asResolvedJavaMethod, (JNIEnv* env, jobject, jobject executable_handle))
385 requireInHotSpot("asResolvedJavaMethod", JVMCI_CHECK_NULL);
386 oop executable = JNIHandles::resolve(executable_handle);
387 oop mirror = nullptr;
388 int slot = 0;
389
390 if (executable->klass() == vmClasses::reflect_Constructor_klass()) {
391 mirror = java_lang_reflect_Constructor::clazz(executable);
392 slot = java_lang_reflect_Constructor::slot(executable);
393 } else {
394 assert(executable->klass() == vmClasses::reflect_Method_klass(), "wrong type");
395 mirror = java_lang_reflect_Method::clazz(executable);
396 slot = java_lang_reflect_Method::slot(executable);
397 }
398 Klass* holder = java_lang_Class::as_Klass(mirror);
399 methodHandle method (THREAD, InstanceKlass::cast(holder)->method_with_idnum(slot));
400 JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
401 return JVMCIENV->get_jobject(result);
402 }
403
404 C2V_VMENTRY_PREFIX(jboolean, updateCompilerThreadCanCallJava, (JNIEnv* env, jobject, jboolean newState))
405 return CompilerThreadCanCallJava::update(thread, newState) != nullptr;
406 C2V_END
407
408
409 C2V_VMENTRY_NULL(jobject, getResolvedJavaMethod, (JNIEnv* env, jobject, jobject base, jlong offset))
410 Method* method = nullptr;
411 JVMCIObject base_object = JVMCIENV->wrap(base);
412 if (base_object.is_null()) {
413 method = *((Method**)(offset));
414 } else {
415 Handle obj = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
416 if (obj->is_a(vmClasses::ResolvedMethodName_klass())) {
417 method = (Method*) (intptr_t) obj->long_field(offset);
418 } else {
419 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", obj->klass()->external_name()));
420 }
421 }
422 if (method == nullptr) {
423 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", JVMCIENV->klass_name(base_object)));
424 }
425 assert (method->is_method(), "invalid read");
426 JVMCIObject result = JVMCIENV->get_jvmci_method(methodHandle(THREAD, method), JVMCI_CHECK_NULL);
427 return JVMCIENV->get_jobject(result);
428 }
429
430 C2V_VMENTRY_NULL(jobject, getConstantPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass_or_method), jboolean is_klass))
431 ConstantPool* cp = nullptr;
432 if (UNPACK_PAIR(address, klass_or_method) == nullptr) {
433 JVMCI_THROW_NULL(NullPointerException);
434 }
435 if (!is_klass) {
436 cp = (UNPACK_PAIR(Method, klass_or_method))->constMethod()->constants();
437 } else {
438 cp = InstanceKlass::cast(UNPACK_PAIR(Klass, klass_or_method))->constants();
439 }
440
441 JVMCIObject result = JVMCIENV->get_jvmci_constant_pool(constantPoolHandle(THREAD, cp), JVMCI_CHECK_NULL);
442 return JVMCIENV->get_jobject(result);
443 }
444
445 C2V_VMENTRY_NULL(jobject, getResolvedJavaType0, (JNIEnv* env, jobject, jobject base, jlong offset, jboolean compressed))
446 JVMCIObject base_object = JVMCIENV->wrap(base);
447 if (base_object.is_null()) {
448 JVMCI_THROW_MSG_NULL(NullPointerException, "base object is null");
449 }
450
451 const char* base_desc = nullptr;
452 JVMCIKlassHandle klass(THREAD);
453 if (offset == 1 /*oopDesc::klass_offset_in_bytes()*/) {
454 if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
455 Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
456 klass = base_oop->klass();
457 } else {
458 goto unexpected;
459 }
460 } else if (!compressed) {
461 if (JVMCIENV->isa_HotSpotConstantPool(base_object)) {
462 ConstantPool* cp = JVMCIENV->asConstantPool(base_object);
463 if (offset == in_bytes(ConstantPool::pool_holder_offset())) {
464 klass = cp->pool_holder();
465 } else {
466 base_desc = FormatBufferResource("[constant pool for %s]", cp->pool_holder()->signature_name());
467 goto unexpected;
468 }
469 } else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base_object)) {
470 Klass* base_klass = JVMCIENV->asKlass(base_object);
471 if (offset == in_bytes(Klass::subklass_offset())) {
472 klass = base_klass->subklass();
473 } else if (offset == in_bytes(Klass::super_offset())) {
474 klass = base_klass->super();
475 } else if (offset == in_bytes(Klass::next_sibling_offset())) {
476 klass = base_klass->next_sibling();
477 } else if (offset == in_bytes(ObjArrayKlass::element_klass_offset()) && base_klass->is_objArray_klass()) {
478 klass = ObjArrayKlass::cast(base_klass)->element_klass();
479 } else if (offset >= in_bytes(Klass::primary_supers_offset()) &&
480 offset < in_bytes(Klass::primary_supers_offset()) + (int) (sizeof(Klass*) * Klass::primary_super_limit()) &&
481 offset % sizeof(Klass*) == 0) {
482 // Offset is within the primary supers array
483 int index = (int) ((offset - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*));
484 klass = base_klass->primary_super_of_depth(index);
485 } else {
486 base_desc = FormatBufferResource("[%s]", base_klass->signature_name());
487 goto unexpected;
488 }
489 } else if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
490 Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
491 if (base_oop->is_a(vmClasses::Class_klass())) {
492 if (offset == java_lang_Class::klass_offset()) {
493 klass = java_lang_Class::as_Klass(base_oop());
494 } else if (offset == java_lang_Class::array_klass_offset()) {
495 klass = java_lang_Class::array_klass_acquire(base_oop());
496 } else {
497 base_desc = FormatBufferResource("[Class=%s]", java_lang_Class::as_Klass(base_oop())->signature_name());
498 goto unexpected;
499 }
500 } else {
501 if (!base_oop.is_null()) {
502 base_desc = FormatBufferResource("[%s]", base_oop()->klass()->signature_name());
503 }
504 goto unexpected;
505 }
506 } else if (JVMCIENV->isa_HotSpotMethodData(base_object)) {
507 jlong base_address = (intptr_t) JVMCIENV->asMethodData(base_object);
508 klass = *((Klass**) (intptr_t) (base_address + offset));
509 if (klass == nullptr || !klass->is_loader_alive()) {
510 // Klasses in methodData might be concurrently unloading so return null in that case.
511 return nullptr;
512 }
513 } else {
514 goto unexpected;
515 }
516 } else {
517 goto unexpected;
518 }
519
520 {
521 if (klass == nullptr) {
522 return nullptr;
523 }
524 JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
525 return JVMCIENV->get_jobject(result);
526 }
527
528 unexpected:
529 JVMCI_THROW_MSG_NULL(IllegalArgumentException,
530 err_msg("Unexpected arguments: %s%s " JLONG_FORMAT " %s",
531 JVMCIENV->klass_name(base_object), base_desc == nullptr ? "" : base_desc,
532 offset, compressed ? "true" : "false"));
533 }
534
535 C2V_VMENTRY_NULL(jobject, findUniqueConcreteMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(method)))
536 methodHandle method (THREAD, UNPACK_PAIR(Method, method));
537 InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
538 if (holder->is_interface()) {
539 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Interface %s should be handled in Java code", holder->external_name()));
540 }
541 if (method->can_be_statically_bound()) {
542 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Effectively static method %s.%s should be handled in Java code", method->method_holder()->external_name(), method->external_name()));
543 }
544
545 methodHandle ucm;
546 {
547 MutexLocker locker(Compile_lock);
548 ucm = methodHandle(THREAD, Dependencies::find_unique_concrete_method(holder, method()));
549 }
550 JVMCIObject result = JVMCIENV->get_jvmci_method(ucm, JVMCI_CHECK_NULL);
551 return JVMCIENV->get_jobject(result);
552 C2V_END
553
554 C2V_VMENTRY_NULL(jobject, getImplementor, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
555 Klass* klass = UNPACK_PAIR(Klass, klass);
556 if (!klass->is_interface()) {
557 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
558 err_msg("Expected interface type, got %s", klass->external_name()));
559 }
560 InstanceKlass* iklass = InstanceKlass::cast(klass);
561 JVMCIKlassHandle handle(THREAD, iklass->implementor());
562 JVMCIObject implementor = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
563 return JVMCIENV->get_jobject(implementor);
564 C2V_END
565
566 C2V_VMENTRY_0(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
567 Method* method = UNPACK_PAIR(Method, method);
568 return method->is_ignored_by_security_stack_walk();
569 C2V_END
570
571 C2V_VMENTRY_0(jboolean, isCompilable,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
572 Method* method = UNPACK_PAIR(Method, method);
573 // Skip redefined methods
574 if (method->is_old()) {
575 return false;
576 }
577 return !method->is_not_compilable(CompLevel_full_optimization);
578 C2V_END
579
580 C2V_VMENTRY_0(jboolean, hasNeverInlineDirective,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
581 methodHandle method (THREAD, UNPACK_PAIR(Method, method));
582 return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
583 C2V_END
584
585 C2V_VMENTRY_0(jboolean, shouldInlineMethod,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
586 methodHandle method (THREAD, UNPACK_PAIR(Method, method));
587 return CompilerOracle::should_inline(method) || method->force_inline();
588 C2V_END
589
590 C2V_VMENTRY_NULL(jobject, lookupType, (JNIEnv* env, jobject, jstring jname, ARGUMENT_PAIR(accessing_klass), jint accessing_klass_loader, jboolean resolve))
591 CompilerThreadCanCallJava canCallJava(thread, resolve); // Resolution requires Java calls
592 JVMCIObject name = JVMCIENV->wrap(jname);
593 const char* str = JVMCIENV->as_utf8_string(name);
594 TempNewSymbol class_name = SymbolTable::new_symbol(str);
595
596 if (class_name->utf8_length() <= 1) {
597 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Primitive type %s should be handled in Java code", str));
598 }
599
600 #ifdef ASSERT
601 const char* val = Arguments::PropertyList_get_value(Arguments::system_properties(), "test.jvmci.lookupTypeException");
602 if (val != nullptr) {
603 if (strstr(val, "<trace>") != nullptr) {
604 tty->print_cr("CompilerToVM.lookupType: %s", str);
605 } else if (strstr(str, val) != nullptr) {
606 THROW_MSG_NULL(vmSymbols::java_lang_Exception(),
607 err_msg("lookupTypeException: %s", str));
608 }
609 }
610 #endif
611
612 JVMCIKlassHandle resolved_klass(THREAD);
613 Klass* accessing_klass = UNPACK_PAIR(Klass, accessing_klass);
614 Handle class_loader;
615 if (accessing_klass != nullptr) {
616 class_loader = Handle(THREAD, accessing_klass->class_loader());
617 } else {
618 switch (accessing_klass_loader) {
619 case 0: break; // class_loader is already null, the boot loader
620 case 1: class_loader = Handle(THREAD, SystemDictionary::java_platform_loader()); break;
621 case 2: class_loader = Handle(THREAD, SystemDictionary::java_system_loader()); break;
622 default:
623 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Illegal class loader value: %d", accessing_klass_loader));
624 }
625 JVMCIENV->runtime()->initialize(JVMCI_CHECK_NULL);
626 }
627
628 if (resolve) {
629 resolved_klass = SystemDictionary::resolve_or_fail(class_name, class_loader, true, CHECK_NULL);
630 } else {
631 if (Signature::has_envelope(class_name)) {
632 // This is a name from a signature. Strip off the trimmings.
633 // Call recursive to keep scope of strippedsym.
634 TempNewSymbol strippedsym = Signature::strip_envelope(class_name);
635 resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
636 class_loader);
637 } else if (Signature::is_array(class_name)) {
638 SignatureStream ss(class_name, false);
639 int ndim = ss.skip_array_prefix();
640 if (ss.type() == T_OBJECT) {
641 Symbol* strippedsym = ss.as_symbol();
642 resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
643 class_loader);
644 if (!resolved_klass.is_null()) {
645 resolved_klass = resolved_klass->array_klass(ndim, CHECK_NULL);
646 }
647 } else {
648 resolved_klass = Universe::typeArrayKlass(ss.type())->array_klass(ndim, CHECK_NULL);
649 }
650 } else {
651 resolved_klass = SystemDictionary::find_instance_klass(THREAD, class_name,
652 class_loader);
653 }
654 }
655 JVMCIObject result = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
656 return JVMCIENV->get_jobject(result);
657 C2V_END
658
659 C2V_VMENTRY_NULL(jobject, getArrayType, (JNIEnv* env, jobject, jchar type_char, ARGUMENT_PAIR(klass)))
660 JVMCIKlassHandle array_klass(THREAD);
661 Klass* klass = UNPACK_PAIR(Klass, klass);
662 if (klass == nullptr) {
663 BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_NULL);
664 if (type == T_VOID) {
665 return nullptr;
666 }
667 array_klass = Universe::typeArrayKlass(type);
668 if (array_klass == nullptr) {
669 JVMCI_THROW_MSG_NULL(InternalError, err_msg("No array klass for primitive type %s", type2name(type)));
670 }
671 } else {
672 array_klass = klass->array_klass(CHECK_NULL);
673 }
674 JVMCIObject result = JVMCIENV->get_jvmci_type(array_klass, JVMCI_CHECK_NULL);
675 return JVMCIENV->get_jobject(result);
676 C2V_END
677
678 C2V_VMENTRY_NULL(jobject, lookupClass, (JNIEnv* env, jobject, jclass mirror))
679 requireInHotSpot("lookupClass", JVMCI_CHECK_NULL);
680 if (mirror == nullptr) {
681 return nullptr;
682 }
683 JVMCIKlassHandle klass(THREAD);
684 klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
685 if (klass == nullptr) {
686 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Primitive classes are unsupported");
687 }
688 JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
689 return JVMCIENV->get_jobject(result);
690 C2V_END
691
692 C2V_VMENTRY_NULL(jobject, lookupJClass, (JNIEnv* env, jobject, jlong jclass_value))
693 if (jclass_value == 0L) {
694 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass must not be zero");
695 }
696 jclass mirror = reinterpret_cast<jclass>(jclass_value);
697 // Since the jclass_value is passed as a jlong, we perform additional checks to prevent the caller from accidentally
698 // sending a value that is not a JNI handle.
699 if (JNIHandles::handle_type(thread, mirror) == JNIInvalidRefType) {
700 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass is not a valid JNI reference");
701 }
702 oop obj = JNIHandles::resolve(mirror);
703 if (!java_lang_Class::is_instance(obj)) {
704 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "jclass must be a reference to the Class object");
705 }
706 JVMCIKlassHandle klass(THREAD, java_lang_Class::as_Klass(obj));
707 JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
708 return JVMCIENV->get_jobject(result);
709 C2V_END
710
711 C2V_VMENTRY_0(jlong, getJObjectValue, (JNIEnv* env, jobject, jobject constant_jobject))
712 requireNotInHotSpot("getJObjectValue", JVMCI_CHECK_0);
713 // Ensure that current JNI handle scope is not the top-most JNIHandleBlock as handles
714 // in that scope are only released when the thread exits.
715 if (!THREAD->has_last_Java_frame() && THREAD->active_handles()->pop_frame_link() == nullptr) {
716 JVMCI_THROW_MSG_0(IllegalStateException, err_msg("Cannot call getJObjectValue without Java frame anchor or a pushed JNI handle block"));
717 }
718 JVMCIObject constant = JVMCIENV->wrap(constant_jobject);
719 Handle constant_value = JVMCIENV->asConstant(constant, JVMCI_CHECK_0);
720 jobject jni_handle = JNIHandles::make_local(THREAD, constant_value());
721 return reinterpret_cast<jlong>(jni_handle);
722 C2V_END
723
724 C2V_VMENTRY_NULL(jobject, getUncachedStringInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
725 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
726 constantTag tag = cp->tag_at(index);
727 if (!tag.is_string()) {
728 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected constant pool tag at index %d: %d", index, tag.value()));
729 }
730 oop obj = cp->uncached_string_at(index, CHECK_NULL);
731 return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(obj));
732 C2V_END
733
734 C2V_VMENTRY_NULL(jobject, lookupConstantInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint cp_index, bool resolve))
735 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
736 oop obj;
737 if (!resolve) {
738 bool found_it;
739 obj = cp->find_cached_constant_at(cp_index, found_it, CHECK_NULL);
740 if (!found_it) {
741 return nullptr;
742 }
743 } else {
744 obj = cp->resolve_possibly_cached_constant_at(cp_index, CHECK_NULL);
745 }
746 constantTag tag = cp->tag_at(cp_index);
747 if (tag.is_dynamic_constant()) {
748 if (obj == nullptr) {
749 return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
750 }
751 BasicType bt = Signature::basic_type(cp->uncached_signature_ref_at(cp_index));
752 if (!is_reference_type(bt)) {
753 if (!is_java_primitive(bt)) {
754 return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_ILLEGAL());
755 }
756
757 // Convert standard box (e.g. java.lang.Integer) to JVMCI box (e.g. jdk.vm.ci.meta.PrimitiveConstant)
758 jvalue value;
759 jlong raw_value;
760 jchar type_char;
761 BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);
762 assert(bt2 == bt, "");
763 switch (bt2) {
764 case T_LONG: type_char = 'J'; raw_value = value.j; break;
765 case T_DOUBLE: type_char = 'D'; raw_value = value.j; break;
766 case T_FLOAT: type_char = 'F'; raw_value = value.i; break;
767 case T_INT: type_char = 'I'; raw_value = value.i; break;
768 case T_SHORT: type_char = 'S'; raw_value = value.s; break;
769 case T_BYTE: type_char = 'B'; raw_value = value.b; break;
770 case T_CHAR: type_char = 'C'; raw_value = value.c; break;
771 case T_BOOLEAN: type_char = 'Z'; raw_value = value.z; break;
772 default: return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_ILLEGAL());
773 }
774
775 JVMCIObject result = JVMCIENV->call_JavaConstant_forPrimitive(type_char, raw_value, JVMCI_CHECK_NULL);
776 return JVMCIENV->get_jobject(result);
777 }
778 }
779 #ifdef ASSERT
780 // Support for testing an OOME raised in a context where the current thread cannot call Java
781 // 1. Put -Dtest.jvmci.oome_in_lookupConstantInPool=<trace> on the command line to
782 // discover possible values for step 2.
783 // Example output:
784 //
785 // CompilerToVM.lookupConstantInPool: "Overflow: String length out of range"{0x00000007ffeb2960}
786 // CompilerToVM.lookupConstantInPool: "null"{0x00000007ffebdfe8}
787 // CompilerToVM.lookupConstantInPool: "Maximum lock count exceeded"{0x00000007ffec4f90}
788 // CompilerToVM.lookupConstantInPool: "Negative length"{0x00000007ffec4468}
789 //
790 // 2. Choose a value shown in step 1.
791 // Example: -Dtest.jvmci.oome_in_lookupConstantInPool=Negative
792 const char* val = Arguments::PropertyList_get_value(Arguments::system_properties(), "test.jvmci.oome_in_lookupConstantInPool");
793 if (val != nullptr) {
794 const char* str = obj->print_value_string();
795 if (strstr(val, "<trace>") != nullptr) {
796 tty->print_cr("CompilerToVM.lookupConstantInPool: %s", str);
797 } else if (strstr(str, val) != nullptr) {
798 Handle garbage;
799 while (true) {
800 // Trigger an OutOfMemoryError
801 objArrayOop next = oopFactory::new_objectArray(0x7FFFFFFF, CHECK_NULL);
802 next->obj_at_put(0, garbage());
803 garbage = Handle(THREAD, next);
804 }
805 }
806 }
807 #endif
808 return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(obj));
809 C2V_END
810
811 C2V_VMENTRY_NULL(jobjectArray, resolveBootstrapMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
812 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
813 constantTag tag = cp->tag_at(index);
814 bool is_indy = tag.is_invoke_dynamic();
815 bool is_condy = tag.is_dynamic_constant();
816 if (!(is_condy || is_indy)) {
817 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected constant pool tag at index %d: %d", index, tag.value()));
818 }
819 // Get the indy entry based on CP index
820 int indy_index = -1;
821 if (is_indy) {
822 for (int i = 0; i < cp->resolved_indy_entries_length(); i++) {
823 if (cp->resolved_indy_entry_at(i)->constant_pool_index() == index) {
824 indy_index = i;
825 }
826 }
827 }
828 // Resolve the bootstrap specifier, its name, type, and static arguments
829 BootstrapInfo bootstrap_specifier(cp, index, indy_index);
830 Handle bsm = bootstrap_specifier.resolve_bsm(CHECK_NULL);
831
832 // call java.lang.invoke.MethodHandle::asFixedArity() -> MethodHandle
833 // to get a DirectMethodHandle from which we can then extract a Method*
834 JavaValue result(T_OBJECT);
835 JavaCalls::call_virtual(&result,
836 bsm,
837 vmClasses::MethodHandle_klass(),
838 vmSymbols::asFixedArity_name(),
839 vmSymbols::asFixedArity_signature(),
840 CHECK_NULL);
841 bsm = Handle(THREAD, result.get_oop());
842
843 // Check assumption about getting a DirectMethodHandle
844 if (!java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
845 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Unexpected MethodHandle subclass: %s", bsm->klass()->external_name()));
846 }
847 // Create return array describing the bootstrap method invocation (BSMI)
848 JVMCIObjectArray bsmi = JVMCIENV->new_Object_array(4, JVMCI_CHECK_NULL);
849
850 // Extract Method* and wrap it in a ResolvedJavaMethod
851 Handle member = Handle(THREAD, java_lang_invoke_DirectMethodHandle::member(bsm()));
852 JVMCIObject bsmi_method = JVMCIENV->get_jvmci_method(methodHandle(THREAD, java_lang_invoke_MemberName::vmtarget(member())), JVMCI_CHECK_NULL);
853 JVMCIENV->put_object_at(bsmi, 0, bsmi_method);
854
855 JVMCIObject bsmi_name = JVMCIENV->create_string(bootstrap_specifier.name(), JVMCI_CHECK_NULL);
856 JVMCIENV->put_object_at(bsmi, 1, bsmi_name);
857
858 Handle type_arg = bootstrap_specifier.type_arg();
859 JVMCIObject bsmi_type = JVMCIENV->get_object_constant(type_arg());
860 JVMCIENV->put_object_at(bsmi, 2, bsmi_type);
861
862 Handle arg_values = bootstrap_specifier.arg_values();
863 if (arg_values.not_null()) {
864 if (!arg_values->is_array()) {
865 JVMCIENV->put_object_at(bsmi, 3, JVMCIENV->get_object_constant(arg_values()));
866 } else if (arg_values->is_objArray()) {
867 objArrayHandle args_array = objArrayHandle(THREAD, (objArrayOop) arg_values());
868 int len = args_array->length();
869 JVMCIObjectArray arguments = JVMCIENV->new_JavaConstant_array(len, JVMCI_CHECK_NULL);
870 JVMCIENV->put_object_at(bsmi, 3, arguments);
871 for (int i = 0; i < len; i++) {
872 oop x = args_array->obj_at(i);
873 if (x != nullptr) {
874 JVMCIENV->put_object_at(arguments, i, JVMCIENV->get_object_constant(x));
875 } else {
876 JVMCIENV->put_object_at(arguments, i, JVMCIENV->get_JavaConstant_NULL_POINTER());
877 }
878 }
879 } else if (arg_values->is_typeArray()) {
880 typeArrayHandle bsci = typeArrayHandle(THREAD, (typeArrayOop) arg_values());
881 JVMCIPrimitiveArray arguments = JVMCIENV->new_intArray(bsci->length(), JVMCI_CHECK_NULL);
882 JVMCIENV->put_object_at(bsmi, 3, arguments);
883 for (int i = 0; i < bsci->length(); i++) {
884 JVMCIENV->put_int_at(arguments, i, bsci->int_at(i));
885 }
886 }
887 }
888 return JVMCIENV->get_jobjectArray(bsmi);
889 C2V_END
890
891 C2V_VMENTRY_0(jint, bootstrapArgumentIndexAt, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint cpi, jint index))
892 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
893 return cp->bootstrap_argument_index_at(cpi, index);
894 C2V_END
895
896 C2V_VMENTRY_0(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
897 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
898 return cp->name_and_type_ref_index_at(index, (Bytecodes::Code)opcode);
899 C2V_END
900
901 C2V_VMENTRY_NULL(jobject, lookupNameInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
902 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
903 JVMCIObject sym = JVMCIENV->create_string(cp->name_ref_at(which, (Bytecodes::Code)opcode), JVMCI_CHECK_NULL);
904 return JVMCIENV->get_jobject(sym);
905 C2V_END
906
907 C2V_VMENTRY_NULL(jobject, lookupSignatureInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
908 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
909 JVMCIObject sym = JVMCIENV->create_string(cp->signature_ref_at(which, (Bytecodes::Code)opcode), JVMCI_CHECK_NULL);
910 return JVMCIENV->get_jobject(sym);
911 C2V_END
912
913 C2V_VMENTRY_0(jint, lookupKlassRefIndexInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
914 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
915 return cp->klass_ref_index_at(index, (Bytecodes::Code)opcode);
916 C2V_END
917
918 C2V_VMENTRY_NULL(jobject, resolveTypeInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
919 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
920 Klass* klass = cp->klass_at(index, CHECK_NULL);
921 JVMCIKlassHandle resolved_klass(THREAD, klass);
922 if (resolved_klass->is_instance_klass()) {
923 InstanceKlass::cast(resolved_klass())->link_class(CHECK_NULL);
924 if (!InstanceKlass::cast(resolved_klass())->is_linked()) {
925 // link_class() should not return here if there is an issue.
926 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be linked", resolved_klass()->external_name()));
927 }
928 }
929 JVMCIObject klassObject = JVMCIENV->get_jvmci_type(resolved_klass, JVMCI_CHECK_NULL);
930 return JVMCIENV->get_jobject(klassObject);
931 C2V_END
932
933 C2V_VMENTRY_NULL(jobject, lookupKlassInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
934 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
935 Klass* loading_klass = cp->pool_holder();
936 bool is_accessible = false;
937 JVMCIKlassHandle klass(THREAD, JVMCIRuntime::get_klass_by_index(cp, index, is_accessible, loading_klass));
938 Symbol* symbol = nullptr;
939 if (klass.is_null()) {
940 constantTag tag = cp->tag_at(index);
941 if (tag.is_klass()) {
942 // The klass has been inserted into the constant pool
943 // very recently.
944 klass = cp->resolved_klass_at(index);
945 } else if (tag.is_symbol()) {
946 symbol = cp->symbol_at(index);
947 } else {
948 if (!tag.is_unresolved_klass()) {
949 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Expected %d at index %d, got %d", JVM_CONSTANT_UnresolvedClassInError, index, tag.value()));
950 }
951 symbol = cp->klass_name_at(index);
952 }
953 }
954 JVMCIObject result;
955 if (!klass.is_null()) {
956 result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
957 } else {
958 result = JVMCIENV->create_string(symbol, JVMCI_CHECK_NULL);
959 }
960 return JVMCIENV->get_jobject(result);
961 C2V_END
962
963 C2V_VMENTRY_NULL(jobject, lookupAppendixInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint which, jint opcode))
964 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
965 oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, which, Bytecodes::Code(opcode));
966 return JVMCIENV->get_jobject(JVMCIENV->get_object_constant(appendix_oop));
967 C2V_END
968
969 C2V_VMENTRY_NULL(jobject, lookupMethodInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jbyte opcode, ARGUMENT_PAIR(caller)))
970 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
971 methodHandle caller(THREAD, UNPACK_PAIR(Method, caller));
972 InstanceKlass* pool_holder = cp->pool_holder();
973 Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
974 methodHandle method(THREAD, JVMCIRuntime::get_method_by_index(cp, index, bc, pool_holder));
975 JFR_ONLY(if (method.not_null()) Jfr::on_resolution(caller(), method(), CHECK_NULL);)
976 JVMCIObject result = JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_NULL);
977 return JVMCIENV->get_jobject(result);
978 C2V_END
979
980 C2V_VMENTRY_NULL(jobject, resolveFieldInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, ARGUMENT_PAIR(method), jbyte opcode, jintArray info_handle))
981 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
982 Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
983 fieldDescriptor fd;
984 methodHandle mh(THREAD, UNPACK_PAIR(Method, method));
985
986 Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
987 int holder_index = cp->klass_ref_index_at(index, bc);
988 if (!cp->tag_at(holder_index).is_klass() && !THREAD->can_call_java()) {
989 // If the holder is not resolved in the constant pool and the current
990 // thread cannot call Java, return null. This avoids a Java call
991 // in LinkInfo to load the holder.
992 Symbol* klass_name = cp->klass_ref_at_noresolve(index, bc);
993 return nullptr;
994 }
995
996 LinkInfo link_info(cp, index, mh, code, CHECK_NULL);
997 LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_NULL);
998 JVMCIPrimitiveArray info = JVMCIENV->wrap(info_handle);
999 if (info.is_null() || JVMCIENV->get_length(info) != 4) {
1000 JVMCI_ERROR_NULL("info must not be null and have a length of 4");
1001 }
1002 JVMCIENV->put_int_at(info, 0, fd.access_flags().as_field_flags());
1003 JVMCIENV->put_int_at(info, 1, fd.offset());
1004 JVMCIENV->put_int_at(info, 2, fd.index());
1005 JVMCIENV->put_int_at(info, 3, fd.field_flags().as_uint());
1006 JVMCIKlassHandle handle(THREAD, fd.field_holder());
1007 JVMCIObject field_holder = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
1008 return JVMCIENV->get_jobject(field_holder);
1009 C2V_END
1010
1011 C2V_VMENTRY_0(jint, getVtableIndexForInterfaceMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(method)))
1012 Klass* klass = UNPACK_PAIR(Klass, klass);
1013 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1014 InstanceKlass* holder = method->method_holder();
1015 if (klass->is_interface()) {
1016 JVMCI_THROW_MSG_0(InternalError, err_msg("Interface %s should be handled in Java code", klass->external_name()));
1017 }
1018 if (!holder->is_interface()) {
1019 JVMCI_THROW_MSG_0(InternalError, err_msg("Method %s is not held by an interface, this case should be handled in Java code", method->name_and_sig_as_C_string()));
1020 }
1021 if (!klass->is_instance_klass()) {
1022 JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
1023 }
1024 if (!InstanceKlass::cast(klass)->is_linked()) {
1025 JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s must be linked", klass->external_name()));
1026 }
1027 if (!klass->is_subtype_of(holder)) {
1028 JVMCI_THROW_MSG_0(InternalError, err_msg("Class %s does not implement interface %s", klass->external_name(), holder->external_name()));
1029 }
1030 return LinkResolver::vtable_index_of_interface_method(klass, method);
1031 C2V_END
1032
1033 C2V_VMENTRY_NULL(jobject, resolveMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(receiver), ARGUMENT_PAIR(method), ARGUMENT_PAIR(caller)))
1034 Klass* recv_klass = UNPACK_PAIR(Klass, receiver);
1035 Klass* caller_klass = UNPACK_PAIR(Klass, caller);
1036 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1037
1038 Klass* resolved = method->method_holder();
1039 Symbol* h_name = method->name();
1040 Symbol* h_signature = method->signature();
1041
1042 if (MethodHandles::is_signature_polymorphic_method(method())) {
1043 // Signature polymorphic methods are already resolved, JVMCI just returns null in this case.
1044 return nullptr;
1045 }
1046
1047 if (method->name() == vmSymbols::clone_name() &&
1048 resolved == vmClasses::Object_klass() &&
1049 recv_klass->is_array_klass()) {
1050 // Resolution of the clone method on arrays always returns Object.clone even though that method
1051 // has protected access. There's some trickery in the access checking to make this all work out
1052 // so it's necessary to pass in the array class as the resolved class to properly trigger this.
1053 // Otherwise it's impossible to resolve the array clone methods through JVMCI. See
1054 // LinkResolver::check_method_accessability for the matching logic.
1055 resolved = recv_klass;
1056 }
1057
1058 LinkInfo link_info(resolved, h_name, h_signature, caller_klass);
1059 Method* m = nullptr;
1060 // Only do exact lookup if receiver klass has been linked. Otherwise,
1061 // the vtable has not been setup, and the LinkResolver will fail.
1062 if (recv_klass->is_array_klass() ||
1063 (InstanceKlass::cast(recv_klass)->is_linked() && !recv_klass->is_interface())) {
1064 if (resolved->is_interface()) {
1065 m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
1066 } else {
1067 m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
1068 }
1069 }
1070
1071 if (m == nullptr) {
1072 // Return null if there was a problem with lookup (uninitialized class, etc.)
1073 return nullptr;
1074 }
1075
1076 JVMCIObject result = JVMCIENV->get_jvmci_method(methodHandle(THREAD, m), JVMCI_CHECK_NULL);
1077 return JVMCIENV->get_jobject(result);
1078 C2V_END
1079
1080 C2V_VMENTRY_0(jboolean, hasFinalizableSubclass,(JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1081 Klass* klass = UNPACK_PAIR(Klass, klass);
1082 assert(klass != nullptr, "method must not be called for primitive types");
1083 if (!klass->is_instance_klass()) {
1084 return false;
1085 }
1086 InstanceKlass* iklass = InstanceKlass::cast(klass);
1087 return Dependencies::find_finalizable_subclass(iklass) != nullptr;
1088 C2V_END
1089
1090 C2V_VMENTRY_NULL(jobject, getClassInitializer, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1091 Klass* klass = UNPACK_PAIR(Klass, klass);
1092 if (!klass->is_instance_klass()) {
1093 return nullptr;
1094 }
1095 InstanceKlass* iklass = InstanceKlass::cast(klass);
1096 methodHandle clinit(THREAD, iklass->class_initializer());
1097 JVMCIObject result = JVMCIENV->get_jvmci_method(clinit, JVMCI_CHECK_NULL);
1098 return JVMCIENV->get_jobject(result);
1099 C2V_END
1100
1101 C2V_VMENTRY_0(jlong, getMaxCallTargetOffset, (JNIEnv* env, jobject, jlong addr))
1102 address target_addr = (address) addr;
1103 if (target_addr != nullptr) {
1104 int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
1105 int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
1106 return MAX2(ABS(off_low), ABS(off_high));
1107 }
1108 return -1;
1109 C2V_END
1110
1111 C2V_VMENTRY(void, setNotInlinableOrCompilable,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1112 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1113 method->set_is_not_c1_compilable();
1114 method->set_is_not_c2_compilable();
1115 method->set_dont_inline(true);
1116 C2V_END
1117
1118 C2V_VMENTRY_0(jint, getInstallCodeFlags, (JNIEnv *env, jobject))
1119 int flags = 0;
1120 #ifndef PRODUCT
1121 flags |= 0x0001; // VM will install block comments
1122 flags |= 0x0004; // Enable HotSpotJVMCIRuntime.Option.CodeSerializationTypeInfo if not explicitly set
1123 #endif
1124 if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1125 // VM needs to track method dependencies
1126 flags |= 0x0002;
1127 }
1128 return flags;
1129 C2V_END
1130
1131 C2V_VMENTRY_0(jint, installCode0, (JNIEnv *env, jobject,
1132 jlong compiled_code_buffer,
1133 jlong serialization_ns,
1134 bool with_type_info,
1135 jobject compiled_code,
1136 jobjectArray object_pool,
1137 jobject installed_code,
1138 jlong failed_speculations_address,
1139 jbyteArray speculations_obj))
1140 HandleMark hm(THREAD);
1141 JNIHandleMark jni_hm(thread);
1142
1143 JVMCIObject compiled_code_handle = JVMCIENV->wrap(compiled_code);
1144 objArrayHandle object_pool_handle(thread, JVMCIENV->is_hotspot() ? (objArrayOop) JNIHandles::resolve(object_pool) : nullptr);
1145
1146 CodeBlob* cb = nullptr;
1147 JVMCIObject installed_code_handle = JVMCIENV->wrap(installed_code);
1148 JVMCIPrimitiveArray speculations_handle = JVMCIENV->wrap(speculations_obj);
1149
1150 int speculations_len = JVMCIENV->get_length(speculations_handle);
1151 char* speculations = NEW_RESOURCE_ARRAY(char, speculations_len);
1152 JVMCIENV->copy_bytes_to(speculations_handle, (jbyte*) speculations, 0, speculations_len);
1153
1154 JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK_JNI_ERR);
1155 JVMCICompiler::CodeInstallStats* stats = compiler->code_install_stats(!thread->is_Compiler_thread());
1156 elapsedTimer *timer = stats->timer();
1157 timer->add_nanoseconds(serialization_ns);
1158 TraceTime install_time("installCode", timer);
1159
1160 CodeInstaller installer(JVMCIENV);
1161 JVMCINMethodHandle nmethod_handle(THREAD);
1162
1163 JVMCI::CodeInstallResult result = installer.install(compiler,
1164 compiled_code_buffer,
1165 with_type_info,
1166 compiled_code_handle,
1167 object_pool_handle,
1168 cb,
1169 nmethod_handle,
1170 installed_code_handle,
1171 (FailedSpeculation**)(address) failed_speculations_address,
1172 speculations,
1173 speculations_len,
1174 JVMCI_CHECK_0);
1175
1176 if (PrintCodeCacheOnCompilation) {
1177 stringStream s;
1178 // Dump code cache into a buffer before locking the tty,
1179 {
1180 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1181 CodeCache::print_summary(&s, false);
1182 }
1183 ttyLocker ttyl;
1184 tty->print_raw_cr(s.freeze());
1185 }
1186
1187 if (result != JVMCI::ok) {
1188 assert(cb == nullptr, "should be");
1189 } else {
1190 stats->on_install(cb);
1191 if (installed_code_handle.is_non_null()) {
1192 if (cb->is_nmethod()) {
1193 assert(JVMCIENV->isa_HotSpotNmethod(installed_code_handle), "wrong type");
1194 // Clear the link to an old nmethod first
1195 JVMCIObject nmethod_mirror = installed_code_handle;
1196 JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, true, JVMCI_CHECK_0);
1197 } else {
1198 assert(JVMCIENV->isa_InstalledCode(installed_code_handle), "wrong type");
1199 }
1200 // Initialize the link to the new code blob
1201 JVMCIENV->initialize_installed_code(installed_code_handle, cb, JVMCI_CHECK_0);
1202 }
1203 }
1204 return result;
1205 C2V_END
1206
1207 C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv* env, jobject))
1208 JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK);
1209 CompilerStatistics* stats = compiler->stats();
1210 stats->_standard.reset();
1211 stats->_osr.reset();
1212 C2V_END
1213
1214 C2V_VMENTRY_NULL(jobject, disassembleCodeBlob, (JNIEnv* env, jobject, jobject installedCode))
1215 HandleMark hm(THREAD);
1216
1217 if (installedCode == nullptr) {
1218 JVMCI_THROW_MSG_NULL(NullPointerException, "installedCode is null");
1219 }
1220
1221 JVMCIObject installedCodeObject = JVMCIENV->wrap(installedCode);
1222 CodeBlob* cb = JVMCIENV->get_code_blob(installedCodeObject);
1223 if (cb == nullptr) {
1224 return nullptr;
1225 }
1226
1227 // We don't want the stringStream buffer to resize during disassembly as it
1228 // uses scoped resource memory. If a nested function called during disassembly uses
1229 // a ResourceMark and the buffer expands within the scope of the mark,
1230 // the buffer becomes garbage when that scope is exited. Experience shows that
1231 // the disassembled code is typically about 10x the code size so a fixed buffer
1232 // sized to 20x code size plus a fixed amount for header info should be sufficient.
1233 int bufferSize = cb->code_size() * 20 + 1024;
1234 char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
1235 stringStream st(buffer, bufferSize);
1236 Disassembler::decode(cb, &st);
1237 if (st.size() <= 0) {
1238 return nullptr;
1239 }
1240
1241 JVMCIObject result = JVMCIENV->create_string(st.as_string(), JVMCI_CHECK_NULL);
1242 return JVMCIENV->get_jobject(result);
1243 C2V_END
1244
1245 C2V_VMENTRY_NULL(jobject, getStackTraceElement, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int bci))
1246 HandleMark hm(THREAD);
1247
1248 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1249 JVMCIObject element = JVMCIENV->new_StackTraceElement(method, bci, JVMCI_CHECK_NULL);
1250 return JVMCIENV->get_jobject(element);
1251 C2V_END
1252
1253 C2V_VMENTRY_NULL(jobject, executeHotSpotNmethod, (JNIEnv* env, jobject, jobject args, jobject hs_nmethod))
1254 // The incoming arguments array would have to contain JavaConstants instead of regular objects
1255 // and the return value would have to be wrapped as a JavaConstant.
1256 requireInHotSpot("executeHotSpotNmethod", JVMCI_CHECK_NULL);
1257
1258 HandleMark hm(THREAD);
1259
1260 JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
1261 methodHandle mh;
1262 {
1263 // Reduce the scope of JVMCINMethodHandle so that it isn't alive across the Java call. Once the
1264 // nmethod has been validated and the method is fetched from the nmethod it's fine for the
1265 // nmethod to be reclaimed if necessary.
1266 JVMCINMethodHandle nmethod_handle(THREAD);
1267 nmethod* nm = JVMCIENV->get_nmethod(nmethod_mirror, nmethod_handle);
1268 if (nm == nullptr || !nm->is_in_use()) {
1269 JVMCI_THROW_NULL(InvalidInstalledCodeException);
1270 }
1271 methodHandle nmh(THREAD, nm->method());
1272 mh = nmh;
1273 }
1274 Symbol* signature = mh->signature();
1275 JavaCallArguments jca(mh->size_of_parameters());
1276
1277 JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
1278 JavaValue result(jap.return_type());
1279 jca.set_alternative_target(Handle(THREAD, JNIHandles::resolve(nmethod_mirror.as_jobject())));
1280 JavaCalls::call(&result, mh, &jca, CHECK_NULL);
1281
1282 if (jap.return_type() == T_VOID) {
1283 return nullptr;
1284 } else if (is_reference_type(jap.return_type())) {
1285 return JNIHandles::make_local(THREAD, result.get_oop());
1286 } else {
1287 jvalue *value = (jvalue *) result.get_value_addr();
1288 // Narrow the value down if required (Important on big endian machines)
1289 switch (jap.return_type()) {
1290 case T_BOOLEAN:
1291 value->z = (jboolean) value->i;
1292 break;
1293 case T_BYTE:
1294 value->b = (jbyte) value->i;
1295 break;
1296 case T_CHAR:
1297 value->c = (jchar) value->i;
1298 break;
1299 case T_SHORT:
1300 value->s = (jshort) value->i;
1301 break;
1302 default:
1303 break;
1304 }
1305 JVMCIObject o = JVMCIENV->create_box(jap.return_type(), value, JVMCI_CHECK_NULL);
1306 return JVMCIENV->get_jobject(o);
1307 }
1308 C2V_END
1309
1310 C2V_VMENTRY_NULL(jlongArray, getLineNumberTable, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1311 Method* method = UNPACK_PAIR(Method, method);
1312 if (!method->has_linenumber_table()) {
1313 return nullptr;
1314 }
1315 u2 num_entries = 0;
1316 CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
1317 while (streamForSize.read_pair()) {
1318 num_entries++;
1319 }
1320
1321 CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
1322 JVMCIPrimitiveArray result = JVMCIENV->new_longArray(2 * num_entries, JVMCI_CHECK_NULL);
1323
1324 int i = 0;
1325 jlong value;
1326 while (stream.read_pair()) {
1327 value = ((jlong) stream.bci());
1328 JVMCIENV->put_long_at(result, i, value);
1329 value = ((jlong) stream.line());
1330 JVMCIENV->put_long_at(result, i + 1, value);
1331 i += 2;
1332 }
1333
1334 return (jlongArray) JVMCIENV->get_jobject(result);
1335 C2V_END
1336
1337 C2V_VMENTRY_0(jlong, getLocalVariableTableStart, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1338 Method* method = UNPACK_PAIR(Method, method);
1339 if (!method->has_localvariable_table()) {
1340 return 0;
1341 }
1342 return (jlong) (address) method->localvariable_table_start();
1343 C2V_END
1344
1345 C2V_VMENTRY_0(jint, getLocalVariableTableLength, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1346 Method* method = UNPACK_PAIR(Method, method);
1347 return method->localvariable_table_length();
1348 C2V_END
1349
1350 static MethodData* get_profiling_method_data(const methodHandle& method, TRAPS) {
1351 MethodData* method_data = method->method_data();
1352 if (method_data == nullptr) {
1353 method->build_profiling_method_data(method, CHECK_NULL);
1354 method_data = method->method_data();
1355 if (method_data == nullptr) {
1356 THROW_MSG_NULL(vmSymbols::java_lang_OutOfMemoryError(), "cannot allocate MethodData")
1357 }
1358 }
1359 return method_data;
1360 }
1361
1362 C2V_VMENTRY(void, reprofile, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
1363 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1364 MethodCounters* mcs = method->method_counters();
1365 if (mcs != nullptr) {
1366 mcs->clear_counters();
1367 }
1368 NOT_PRODUCT(method->set_compiled_invocation_count(0));
1369
1370 nmethod* code = method->code();
1371 if (code != nullptr) {
1372 code->make_not_entrant("JVMCI reprofile");
1373 }
1374
1375 MethodData* method_data = method->method_data();
1376 if (method_data == nullptr) {
1377 method_data = get_profiling_method_data(method, CHECK);
1378 } else {
1379 CompilerThreadCanCallJava canCallJava(THREAD, true);
1380 method_data->reinitialize();
1381 }
1382 C2V_END
1383
1384
1385 C2V_VMENTRY(void, invalidateHotSpotNmethod, (JNIEnv* env, jobject, jobject hs_nmethod, jboolean deoptimize))
1386 JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
1387 JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, deoptimize, JVMCI_CHECK);
1388 C2V_END
1389
1390 C2V_VMENTRY_NULL(jlongArray, collectCounters, (JNIEnv* env, jobject))
1391 // Returns a zero length array if counters aren't enabled
1392 JVMCIPrimitiveArray array = JVMCIENV->new_longArray(JVMCICounterSize, JVMCI_CHECK_NULL);
1393 if (JVMCICounterSize > 0) {
1394 jlong* temp_array = NEW_RESOURCE_ARRAY(jlong, JVMCICounterSize);
1395 JavaThread::collect_counters(temp_array, JVMCICounterSize);
1396 JVMCIENV->copy_longs_from(temp_array, array, 0, JVMCICounterSize);
1397 }
1398 return (jlongArray) JVMCIENV->get_jobject(array);
1399 C2V_END
1400
1401 C2V_VMENTRY_0(jint, getCountersSize, (JNIEnv* env, jobject))
1402 return (jint) JVMCICounterSize;
1403 C2V_END
1404
1405 C2V_VMENTRY_0(jboolean, setCountersSize, (JNIEnv* env, jobject, jint new_size))
1406 return JavaThread::resize_all_jvmci_counters(new_size);
1407 C2V_END
1408
1409 C2V_VMENTRY_0(jint, allocateCompileId, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci))
1410 HandleMark hm(THREAD);
1411 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1412 if (method.is_null()) {
1413 JVMCI_THROW_0(NullPointerException);
1414 }
1415 if (entry_bci >= method->code_size() || entry_bci < -1) {
1416 JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Unexpected bci %d", entry_bci));
1417 }
1418 return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
1419 C2V_END
1420
1421
1422 C2V_VMENTRY_0(jboolean, isMature, (JNIEnv* env, jobject, jlong method_data_pointer))
1423 MethodData* mdo = (MethodData*) method_data_pointer;
1424 return mdo != nullptr && mdo->is_mature();
1425 C2V_END
1426
1427 C2V_VMENTRY_0(jboolean, hasCompiledCodeForOSR, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci, int comp_level))
1428 Method* method = UNPACK_PAIR(Method, method);
1429 return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != nullptr;
1430 C2V_END
1431
1432 C2V_VMENTRY_NULL(jobject, getSymbol, (JNIEnv* env, jobject, jlong symbol))
1433 JVMCIObject sym = JVMCIENV->create_string((Symbol*)(address)symbol, JVMCI_CHECK_NULL);
1434 return JVMCIENV->get_jobject(sym);
1435 C2V_END
1436
1437 C2V_VMENTRY_NULL(jobject, getSignatureName, (JNIEnv* env, jobject, jlong klass_pointer))
1438 Klass* klass = UNPACK_PAIR(Klass, klass);
1439 JVMCIObject signature = JVMCIENV->create_string(klass->signature_name(), JVMCI_CHECK_NULL);
1440 return JVMCIENV->get_jobject(signature);
1441 C2V_END
1442
1443 /*
1444 * Used by matches() to convert a ResolvedJavaMethod[] to an array of Method*.
1445 */
1446 static GrowableArray<Method*>* init_resolved_methods(jobjectArray methods, JVMCIEnv* JVMCIENV) {
1447 objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
1448 GrowableArray<Method*>* resolved_methods = new GrowableArray<Method*>(methods_oop->length());
1449 for (int i = 0; i < methods_oop->length(); i++) {
1450 oop resolved = methods_oop->obj_at(i);
1451 Method* resolved_method = nullptr;
1452 if (resolved->klass() == HotSpotJVMCI::HotSpotResolvedJavaMethodImpl::klass()) {
1453 resolved_method = HotSpotJVMCI::asMethod(JVMCIENV, resolved);
1454 }
1455 resolved_methods->append(resolved_method);
1456 }
1457 return resolved_methods;
1458 }
1459
1460 /*
1461 * Used by c2v_iterateFrames to check if `method` matches one of the ResolvedJavaMethods in the `methods` array.
1462 * The ResolvedJavaMethod[] array is converted to a Method* array that is then cached in the resolved_methods_ref in/out parameter.
1463 * In case of a match, the matching ResolvedJavaMethod is returned in matched_jvmci_method_ref.
1464 */
1465 static bool matches(jobjectArray methods, Method* method, GrowableArray<Method*>** resolved_methods_ref, Handle* matched_jvmci_method_ref, Thread* THREAD, JVMCIEnv* JVMCIENV) {
1466 GrowableArray<Method*>* resolved_methods = *resolved_methods_ref;
1467 if (resolved_methods == nullptr) {
1468 resolved_methods = init_resolved_methods(methods, JVMCIENV);
1469 *resolved_methods_ref = resolved_methods;
1470 }
1471 assert(method != nullptr, "method should not be null");
1472 assert(resolved_methods->length() == ((objArrayOop) JNIHandles::resolve(methods))->length(), "arrays must have the same length");
1473 for (int i = 0; i < resolved_methods->length(); i++) {
1474 Method* m = resolved_methods->at(i);
1475 if (m == method) {
1476 *matched_jvmci_method_ref = Handle(THREAD, ((objArrayOop) JNIHandles::resolve(methods))->obj_at(i));
1477 return true;
1478 }
1479 }
1480 return false;
1481 }
1482
1483 /*
1484 * Resolves an interface call to a concrete method handle.
1485 */
1486 static methodHandle resolve_interface_call(Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
1487 CallInfo callinfo;
1488 Handle receiver = args->receiver();
1489 Klass* recvrKlass = receiver.is_null() ? (Klass*)nullptr : receiver->klass();
1490 LinkInfo link_info(spec_klass, name, signature);
1491 LinkResolver::resolve_interface_call(
1492 callinfo, receiver, recvrKlass, link_info, true, CHECK_(methodHandle()));
1493 methodHandle method(THREAD, callinfo.selected_method());
1494 assert(method.not_null(), "should have thrown exception");
1495 return method;
1496 }
1497
1498 /*
1499 * Used by c2v_iterateFrames to make a new vframeStream at the given compiled frame id (stack pointer) and vframe id.
1500 */
1501 static void resync_vframestream_to_compiled_frame(vframeStream& vfst, intptr_t* stack_pointer, int vframe_id, JavaThread* thread, TRAPS) {
1502 vfst = vframeStream(thread);
1503 while (vfst.frame_id() != stack_pointer && !vfst.at_end()) {
1504 vfst.next();
1505 }
1506 if (vfst.frame_id() != stack_pointer) {
1507 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1508 }
1509 if (vfst.is_interpreted_frame()) {
1510 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1511 }
1512 while (vfst.vframe_id() != vframe_id) {
1513 if (vfst.at_end()) {
1514 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
1515 }
1516 vfst.next();
1517 assert(!vfst.is_interpreted_frame(), "Wrong frame type");
1518 }
1519 }
1520
1521 /*
1522 * Used by c2v_iterateFrames. Returns an array of any unallocated scope objects or null if none.
1523 */
1524 static GrowableArray<ScopeValue*>* get_unallocated_objects_or_null(GrowableArray<ScopeValue*>* scope_objects) {
1525 GrowableArray<ScopeValue*>* unallocated = nullptr;
1526 for (int i = 0; i < scope_objects->length(); i++) {
1527 ObjectValue* sv = (ObjectValue*) scope_objects->at(i);
1528 if (sv->value().is_null()) {
1529 if (unallocated == nullptr) {
1530 unallocated = new GrowableArray<ScopeValue*>(scope_objects->length());
1531 }
1532 unallocated->append(sv);
1533 }
1534 }
1535 return unallocated;
1536 }
1537
1538 C2V_VMENTRY_NULL(jobject, iterateFrames, (JNIEnv* env, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
1539
1540 if (!thread->has_last_Java_frame()) {
1541 return nullptr;
1542 }
1543 Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
1544 KeepStackGCProcessedMark keep_stack(THREAD);
1545
1546 requireInHotSpot("iterateFrames", JVMCI_CHECK_NULL);
1547
1548 HotSpotJVMCI::HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1549
1550 vframeStream vfst(thread);
1551 jobjectArray methods = initial_methods;
1552 methodHandle visitor_method;
1553 GrowableArray<Method*>* resolved_methods = nullptr;
1554
1555 while (!vfst.at_end()) { // frame loop
1556 bool realloc_called = false;
1557 intptr_t* frame_id = vfst.frame_id();
1558
1559 // Previous compiledVFrame of this frame; use with at_scope() to reuse scope object pool.
1560 compiledVFrame* prev_cvf = nullptr;
1561
1562 for (; !vfst.at_end() && vfst.frame_id() == frame_id; vfst.next()) { // vframe loop
1563 int frame_number = 0;
1564 Method *method = vfst.method();
1565 int bci = vfst.bci();
1566
1567 Handle matched_jvmci_method;
1568 if (methods == nullptr || matches(methods, method, &resolved_methods, &matched_jvmci_method, THREAD, JVMCIENV)) {
1569 if (initialSkip > 0) {
1570 initialSkip--;
1571 continue;
1572 }
1573 javaVFrame* vf;
1574 if (prev_cvf != nullptr && prev_cvf->frame_pointer()->id() == frame_id) {
1575 assert(prev_cvf->is_compiled_frame(), "expected compiled Java frame");
1576 vf = prev_cvf->at_scope(vfst.decode_offset(), vfst.vframe_id());
1577 } else {
1578 vf = vfst.asJavaVFrame();
1579 }
1580
1581 StackValueCollection* locals = nullptr;
1582 typeArrayHandle localIsVirtual_h;
1583 if (vf->is_compiled_frame()) {
1584 // compiled method frame
1585 compiledVFrame* cvf = compiledVFrame::cast(vf);
1586
1587 ScopeDesc* scope = cvf->scope();
1588 // native wrappers do not have a scope
1589 if (scope != nullptr && scope->objects() != nullptr) {
1590 prev_cvf = cvf;
1591
1592 GrowableArray<ScopeValue*>* objects = nullptr;
1593 if (!realloc_called) {
1594 objects = scope->objects();
1595 } else {
1596 // some object might already have been re-allocated, only reallocate the non-allocated ones
1597 objects = get_unallocated_objects_or_null(scope->objects());
1598 }
1599
1600 if (objects != nullptr) {
1601 RegisterMap reg_map(vf->register_map());
1602 bool realloc_failures = Deoptimization::realloc_objects(thread, vf->frame_pointer(), ®_map, objects, CHECK_NULL);
1603 Deoptimization::reassign_fields(vf->frame_pointer(), ®_map, objects, realloc_failures, false);
1604 realloc_called = true;
1605 }
1606
1607 GrowableArray<ScopeValue*>* local_values = scope->locals();
1608 for (int i = 0; i < local_values->length(); i++) {
1609 ScopeValue* value = local_values->at(i);
1610 assert(!value->is_object_merge(), "Should not be.");
1611 if (value->is_object()) {
1612 if (localIsVirtual_h.is_null()) {
1613 typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
1614 localIsVirtual_h = typeArrayHandle(THREAD, array_oop);
1615 }
1616 localIsVirtual_h->bool_at_put(i, true);
1617 }
1618 }
1619 }
1620
1621 locals = cvf->locals();
1622 frame_number = cvf->vframe_id();
1623 } else {
1624 // interpreted method frame
1625 interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1626
1627 locals = ivf->locals();
1628 }
1629 assert(bci == vf->bci(), "wrong bci");
1630 assert(method == vf->method(), "wrong method");
1631
1632 Handle frame_reference = HotSpotJVMCI::HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1633 HotSpotJVMCI::HotSpotStackFrameReference::set_bci(JVMCIENV, frame_reference(), bci);
1634 if (matched_jvmci_method.is_null()) {
1635 methodHandle mh(THREAD, method);
1636 JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
1637 matched_jvmci_method = Handle(THREAD, JNIHandles::resolve(jvmci_method.as_jobject()));
1638 }
1639 HotSpotJVMCI::HotSpotStackFrameReference::set_method(JVMCIENV, frame_reference(), matched_jvmci_method());
1640 HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), localIsVirtual_h());
1641
1642 HotSpotJVMCI::HotSpotStackFrameReference::set_compilerToVM(JVMCIENV, frame_reference(), JNIHandles::resolve(compilerToVM));
1643 HotSpotJVMCI::HotSpotStackFrameReference::set_stackPointer(JVMCIENV, frame_reference(), (jlong) frame_id);
1644 HotSpotJVMCI::HotSpotStackFrameReference::set_frameNumber(JVMCIENV, frame_reference(), frame_number);
1645
1646 // initialize the locals array
1647 objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
1648 objArrayHandle array(THREAD, array_oop);
1649 for (int i = 0; i < locals->size(); i++) {
1650 StackValue* var = locals->at(i);
1651 if (var->type() == T_OBJECT) {
1652 array->obj_at_put(i, locals->at(i)->get_obj()());
1653 }
1654 }
1655 HotSpotJVMCI::HotSpotStackFrameReference::set_locals(JVMCIENV, frame_reference(), array());
1656 HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, frame_reference(), JNI_FALSE);
1657
1658 JavaValue result(T_OBJECT);
1659 JavaCallArguments args(visitor);
1660 if (visitor_method.is_null()) {
1661 visitor_method = resolve_interface_call(HotSpotJVMCI::InspectedFrameVisitor::klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
1662 }
1663
1664 args.push_oop(frame_reference);
1665 JavaCalls::call(&result, visitor_method, &args, CHECK_NULL);
1666 if (result.get_oop() != nullptr) {
1667 return JNIHandles::make_local(thread, result.get_oop());
1668 }
1669 if (methods == initial_methods) {
1670 methods = match_methods;
1671 if (resolved_methods != nullptr && JNIHandles::resolve(match_methods) != JNIHandles::resolve(initial_methods)) {
1672 resolved_methods = nullptr;
1673 }
1674 }
1675 assert(initialSkip == 0, "There should be no match before initialSkip == 0");
1676 if (HotSpotJVMCI::HotSpotStackFrameReference::objectsMaterialized(JVMCIENV, frame_reference()) == JNI_TRUE) {
1677 // the frame has been deoptimized, we need to re-synchronize the frame and vframe
1678 prev_cvf = nullptr;
1679 intptr_t* stack_pointer = (intptr_t*) HotSpotJVMCI::HotSpotStackFrameReference::stackPointer(JVMCIENV, frame_reference());
1680 resync_vframestream_to_compiled_frame(vfst, stack_pointer, frame_number, thread, CHECK_NULL);
1681 }
1682 }
1683 } // end of vframe loop
1684 } // end of frame loop
1685
1686 // the end was reached without finding a matching method
1687 return nullptr;
1688 C2V_END
1689
1690 C2V_VMENTRY_0(int, decodeIndyIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint indy_index, jboolean resolve))
1691 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1692 CallInfo callInfo;
1693 if (resolve) {
1694 LinkResolver::resolve_invoke(callInfo, Handle(), cp, indy_index, Bytecodes::_invokedynamic, CHECK_0);
1695 cp->cache()->set_dynamic_call(callInfo, indy_index);
1696 }
1697 return cp->resolved_indy_entry_at(indy_index)->constant_pool_index();
1698 C2V_END
1699
1700 C2V_VMENTRY_0(int, decodeFieldIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint field_index))
1701 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1702 if (field_index < 0 || field_index >= cp->resolved_field_entries_length()) {
1703 JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid field index %d", field_index));
1704 }
1705 return cp->resolved_field_entry_at(field_index)->constant_pool_index();
1706 C2V_END
1707
1708 C2V_VMENTRY_0(int, decodeMethodIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint method_index))
1709 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1710 if (method_index < 0 || method_index >= cp->resolved_method_entries_length()) {
1711 JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid method index %d", method_index));
1712 }
1713 return cp->resolved_method_entry_at(method_index)->constant_pool_index();
1714 C2V_END
1715
1716 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
1717 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1718 Klass* holder = cp->klass_ref_at(index, Bytecodes::_invokehandle, CHECK);
1719 Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1720 if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1721 CallInfo callInfo;
1722 LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1723 cp->cache()->set_method_handle(index, callInfo);
1724 }
1725 C2V_END
1726
1727 C2V_VMENTRY_0(jint, isResolvedInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
1728 constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1729 ResolvedMethodEntry* entry = cp->cache()->resolved_method_entry_at(index);
1730 if (entry->is_resolved(Bytecodes::_invokehandle)) {
1731 // MethodHandle.invoke* --> LambdaForm?
1732 ResourceMark rm;
1733
1734 LinkInfo link_info(cp, index, Bytecodes::_invokehandle, CATCH);
1735
1736 Klass* resolved_klass = link_info.resolved_klass();
1737
1738 Symbol* name_sym = cp->name_ref_at(index, Bytecodes::_invokehandle);
1739
1740 vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
1741 vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
1742
1743 methodHandle adapter_method(THREAD, entry->method());
1744
1745 methodHandle resolved_method(adapter_method);
1746
1747 // Can we treat it as a regular invokevirtual?
1748 if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
1749 vmassert(!resolved_method->is_static(),"!");
1750 vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
1751 vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
1752 vmassert(cp->cache()->appendix_if_resolved(entry) == nullptr, "!");
1753
1754 methodHandle m(THREAD, LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
1755 vmassert(m == resolved_method, "!!");
1756 return -1;
1757 }
1758
1759 return Bytecodes::_invokevirtual;
1760 }
1761 if ((Bytecodes::Code)opcode == Bytecodes::_invokedynamic) {
1762 if (cp->resolved_indy_entry_at(index)->is_resolved()) {
1763 return Bytecodes::_invokedynamic;
1764 }
1765 }
1766 return -1;
1767 C2V_END
1768
1769
1770 C2V_VMENTRY_NULL(jobject, getSignaturePolymorphicHolders, (JNIEnv* env, jobject))
1771 JVMCIObjectArray holders = JVMCIENV->new_String_array(2, JVMCI_CHECK_NULL);
1772 JVMCIObject mh = JVMCIENV->create_string("Ljava/lang/invoke/MethodHandle;", JVMCI_CHECK_NULL);
1773 JVMCIObject vh = JVMCIENV->create_string("Ljava/lang/invoke/VarHandle;", JVMCI_CHECK_NULL);
1774 JVMCIENV->put_object_at(holders, 0, mh);
1775 JVMCIENV->put_object_at(holders, 1, vh);
1776 return JVMCIENV->get_jobject(holders);
1777 C2V_END
1778
1779 C2V_VMENTRY_0(jboolean, shouldDebugNonSafepoints, (JNIEnv* env, jobject))
1780 //see compute_recording_non_safepoints in debugInfroRec.cpp
1781 if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1782 return true;
1783 }
1784 return DebugNonSafepoints;
1785 C2V_END
1786
1787 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1788 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv* env, jobject, jobject _hs_frame, bool invalidate))
1789 JVMCIObject hs_frame = JVMCIENV->wrap(_hs_frame);
1790 if (hs_frame.is_null()) {
1791 JVMCI_THROW_MSG(NullPointerException, "stack frame is null");
1792 }
1793
1794 requireInHotSpot("materializeVirtualObjects", JVMCI_CHECK);
1795
1796 JVMCIENV->HotSpotStackFrameReference_initialize(JVMCI_CHECK);
1797
1798 // look for the given stack frame
1799 StackFrameStream fst(thread, false /* update */, true /* process_frames */);
1800 intptr_t* stack_pointer = (intptr_t*) JVMCIENV->get_HotSpotStackFrameReference_stackPointer(hs_frame);
1801 while (fst.current()->id() != stack_pointer && !fst.is_done()) {
1802 fst.next();
1803 }
1804 if (fst.current()->id() != stack_pointer) {
1805 JVMCI_THROW_MSG(IllegalStateException, "stack frame not found");
1806 }
1807
1808 if (invalidate) {
1809 if (!fst.current()->is_compiled_frame()) {
1810 JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1811 }
1812 fst.current()->cb()->as_nmethod()->make_not_entrant("JVMCI materialize virtual objects");
1813 }
1814 Deoptimization::deoptimize(thread, *fst.current(), Deoptimization::Reason_none);
1815 // look for the frame again as it has been updated by deopt (pc, deopt state...)
1816 StackFrameStream fstAfterDeopt(thread, true /* update */, true /* process_frames */);
1817 while (fstAfterDeopt.current()->id() != stack_pointer && !fstAfterDeopt.is_done()) {
1818 fstAfterDeopt.next();
1819 }
1820 if (fstAfterDeopt.current()->id() != stack_pointer) {
1821 JVMCI_THROW_MSG(IllegalStateException, "stack frame not found after deopt");
1822 }
1823
1824 vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1825 if (!vf->is_compiled_frame()) {
1826 JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1827 }
1828
1829 GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1830 while (true) {
1831 assert(vf->is_compiled_frame(), "Wrong frame type");
1832 virtualFrames->push(compiledVFrame::cast(vf));
1833 if (vf->is_top()) {
1834 break;
1835 }
1836 vf = vf->sender();
1837 }
1838
1839 int last_frame_number = JVMCIENV->get_HotSpotStackFrameReference_frameNumber(hs_frame);
1840 if (last_frame_number >= virtualFrames->length()) {
1841 JVMCI_THROW_MSG(IllegalStateException, "invalid frame number");
1842 }
1843
1844 // Reallocate the non-escaping objects and restore their fields.
1845 assert (virtualFrames->at(last_frame_number)->scope() != nullptr,"invalid scope");
1846 GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1847
1848 if (objects == nullptr) {
1849 // no objects to materialize
1850 return;
1851 }
1852
1853 bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, CHECK);
1854 Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
1855
1856 for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1857 compiledVFrame* cvf = virtualFrames->at(frame_index);
1858
1859 GrowableArray<ScopeValue*>* scopedValues = cvf->scope()->locals();
1860 StackValueCollection* locals = cvf->locals();
1861 if (locals != nullptr) {
1862 for (int i2 = 0; i2 < locals->size(); i2++) {
1863 StackValue* var = locals->at(i2);
1864 assert(!scopedValues->at(i2)->is_object_merge(), "Should not be.");
1865 if (var->type() == T_OBJECT && scopedValues->at(i2)->is_object()) {
1866 jvalue val;
1867 val.l = cast_from_oop<jobject>(locals->at(i2)->get_obj()());
1868 cvf->update_local(T_OBJECT, i2, val);
1869 }
1870 }
1871 }
1872
1873 GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
1874 StackValueCollection* expressions = cvf->expressions();
1875 if (expressions != nullptr) {
1876 for (int i2 = 0; i2 < expressions->size(); i2++) {
1877 StackValue* var = expressions->at(i2);
1878 assert(!scopeExpressions->at(i2)->is_object_merge(), "Should not be.");
1879 if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
1880 jvalue val;
1881 val.l = cast_from_oop<jobject>(expressions->at(i2)->get_obj()());
1882 cvf->update_stack(T_OBJECT, i2, val);
1883 }
1884 }
1885 }
1886
1887 GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
1888 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1889 if (monitors != nullptr) {
1890 for (int i2 = 0; i2 < monitors->length(); i2++) {
1891 cvf->update_monitor(i2, monitors->at(i2));
1892 }
1893 }
1894 }
1895
1896 // all locals are materialized by now
1897 JVMCIENV->set_HotSpotStackFrameReference_localIsVirtual(hs_frame, nullptr);
1898 // update the locals array
1899 JVMCIObjectArray array = JVMCIENV->get_HotSpotStackFrameReference_locals(hs_frame);
1900 StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1901 for (int i = 0; i < locals->size(); i++) {
1902 StackValue* var = locals->at(i);
1903 if (var->type() == T_OBJECT) {
1904 JVMCIENV->put_object_at(array, i, HotSpotJVMCI::wrap(locals->at(i)->get_obj()()));
1905 }
1906 }
1907 HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, hs_frame, JNI_TRUE);
1908 C2V_END
1909
1910 // Use of tty does not require the current thread to be attached to the VM
1911 // so no need for a full C2V_VMENTRY transition.
1912 C2V_VMENTRY_PREFIX(void, writeDebugOutput, (JNIEnv* env, jobject, jlong buffer, jint length, bool flush))
1913 if (length <= 8) {
1914 tty->write((char*) &buffer, length);
1915 } else {
1916 tty->write((char*) buffer, length);
1917 }
1918 if (flush) {
1919 tty->flush();
1920 }
1921 C2V_END
1922
1923 // Use of tty does not require the current thread to be attached to the VM
1924 // so no need for a full C2V_VMENTRY transition.
1925 C2V_VMENTRY_PREFIX(void, flushDebugOutput, (JNIEnv* env, jobject))
1926 tty->flush();
1927 C2V_END
1928
1929 C2V_VMENTRY_0(jint, methodDataProfileDataSize, (JNIEnv* env, jobject, jlong method_data_pointer, jint position))
1930 MethodData* mdo = (MethodData*) method_data_pointer;
1931 ProfileData* profile_data = mdo->data_at(position);
1932 if (mdo->is_valid(profile_data)) {
1933 return profile_data->size_in_bytes();
1934 }
1935 // Java code should never directly access the extra data section
1936 JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Invalid profile data position %d", position));
1937 C2V_END
1938
1939 C2V_VMENTRY_0(jint, methodDataExceptionSeen, (JNIEnv* env, jobject, jlong method_data_pointer, jint bci))
1940 MethodData* mdo = (MethodData*) method_data_pointer;
1941
1942 // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1943 MutexLocker mu(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
1944
1945 DataLayout* data = mdo->extra_data_base();
1946 DataLayout* end = mdo->args_data_limit();
1947 for (;; data = mdo->next_extra(data)) {
1948 assert(data < end, "moved past end of extra data");
1949 int tag = data->tag();
1950 switch(tag) {
1951 case DataLayout::bit_data_tag: {
1952 BitData* bit_data = (BitData*) data->data_in();
1953 if (bit_data->bci() == bci) {
1954 return bit_data->exception_seen() ? 1 : 0;
1955 }
1956 break;
1957 }
1958 case DataLayout::no_tag:
1959 // There is a free slot so return false since a BitData would have been allocated to record
1960 // true if it had been seen.
1961 return 0;
1962 case DataLayout::arg_info_data_tag:
1963 // The bci wasn't found and there are no free slots to record a trap for this location, so always
1964 // return unknown.
1965 return -1;
1966 }
1967 }
1968 ShouldNotReachHere();
1969 return -1;
1970 C2V_END
1971
1972 C2V_VMENTRY_NULL(jobject, getInterfaces, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1973 Klass* klass = UNPACK_PAIR(Klass, klass);
1974 if (klass == nullptr) {
1975 JVMCI_THROW_NULL(NullPointerException);
1976 }
1977
1978 if (!klass->is_instance_klass()) {
1979 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
1980 }
1981 InstanceKlass* iklass = InstanceKlass::cast(klass);
1982
1983 // Regular instance klass, fill in all local interfaces
1984 int size = iklass->local_interfaces()->length();
1985 JVMCIObjectArray interfaces = JVMCIENV->new_HotSpotResolvedObjectTypeImpl_array(size, JVMCI_CHECK_NULL);
1986 for (int index = 0; index < size; index++) {
1987 JVMCIKlassHandle klass(THREAD);
1988 Klass* k = iklass->local_interfaces()->at(index);
1989 klass = k;
1990 JVMCIObject type = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
1991 JVMCIENV->put_object_at(interfaces, index, type);
1992 }
1993 return JVMCIENV->get_jobject(interfaces);
1994 C2V_END
1995
1996 C2V_VMENTRY_NULL(jobject, getComponentType, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1997 Klass* klass = UNPACK_PAIR(Klass, klass);
1998 if (klass == nullptr) {
1999 JVMCI_THROW_NULL(NullPointerException);
2000 }
2001
2002 if (!klass->is_array_klass()) {
2003 return nullptr;
2004 }
2005 oop mirror = klass->java_mirror();
2006 oop component_mirror = java_lang_Class::component_mirror(mirror);
2007 if (component_mirror == nullptr) {
2008 JVMCI_THROW_MSG_NULL(NullPointerException,
2009 err_msg("Component mirror for array class %s is null", klass->external_name()))
2010 }
2011
2012 Klass* component_klass = java_lang_Class::as_Klass(component_mirror);
2013 if (component_klass != nullptr) {
2014 JVMCIKlassHandle klass_handle(THREAD, component_klass);
2015 JVMCIObject result = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2016 return JVMCIENV->get_jobject(result);
2017 }
2018 BasicType type = java_lang_Class::primitive_type(component_mirror);
2019 JVMCIObject result = JVMCIENV->get_jvmci_primitive_type(type);
2020 return JVMCIENV->get_jobject(result);
2021 C2V_END
2022
2023 C2V_VMENTRY(void, ensureInitialized, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2024 Klass* klass = UNPACK_PAIR(Klass, klass);
2025 if (klass == nullptr) {
2026 JVMCI_THROW(NullPointerException);
2027 }
2028 if (klass->should_be_initialized()) {
2029 InstanceKlass* k = InstanceKlass::cast(klass);
2030 k->initialize(CHECK);
2031 }
2032 C2V_END
2033
2034 C2V_VMENTRY(void, ensureLinked, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2035 CompilerThreadCanCallJava canCallJava(thread, true); // Linking requires Java calls
2036 Klass* klass = UNPACK_PAIR(Klass, klass);
2037 if (klass == nullptr) {
2038 JVMCI_THROW(NullPointerException);
2039 }
2040 if (klass->is_instance_klass()) {
2041 InstanceKlass* k = InstanceKlass::cast(klass);
2042 k->link_class(CHECK);
2043 }
2044 C2V_END
2045
2046 C2V_VMENTRY_0(jint, interpreterFrameSize, (JNIEnv* env, jobject, jobject bytecode_frame_handle))
2047 if (bytecode_frame_handle == nullptr) {
2048 JVMCI_THROW_0(NullPointerException);
2049 }
2050
2051 JVMCIObject top_bytecode_frame = JVMCIENV->wrap(bytecode_frame_handle);
2052 JVMCIObject bytecode_frame = top_bytecode_frame;
2053 int size = 0;
2054 int callee_parameters = 0;
2055 int callee_locals = 0;
2056 Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2057 int extra_args = method->max_stack() - JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2058
2059 while (bytecode_frame.is_non_null()) {
2060 int locks = JVMCIENV->get_BytecodeFrame_numLocks(bytecode_frame);
2061 int temps = JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2062 bool is_top_frame = (JVMCIENV->equals(bytecode_frame, top_bytecode_frame));
2063 Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2064
2065 int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
2066 temps + callee_parameters,
2067 extra_args,
2068 locks,
2069 callee_parameters,
2070 callee_locals,
2071 is_top_frame);
2072 size += frame_size;
2073
2074 callee_parameters = method->size_of_parameters();
2075 callee_locals = method->max_locals();
2076 extra_args = 0;
2077 bytecode_frame = JVMCIENV->get_BytecodePosition_caller(bytecode_frame);
2078 }
2079 return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
2080 C2V_END
2081
2082 C2V_VMENTRY(void, compileToBytecode, (JNIEnv* env, jobject, jobject lambda_form_handle))
2083 Handle lambda_form = JVMCIENV->asConstant(JVMCIENV->wrap(lambda_form_handle), JVMCI_CHECK);
2084 if (lambda_form->is_a(vmClasses::LambdaForm_klass())) {
2085 TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode");
2086 JavaValue result(T_VOID);
2087 JavaCalls::call_special(&result, lambda_form, vmClasses::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
2088 } else {
2089 JVMCI_THROW_MSG(IllegalArgumentException,
2090 err_msg("Unexpected type: %s", lambda_form->klass()->external_name()))
2091 }
2092 C2V_END
2093
2094 C2V_VMENTRY_0(jint, getIdentityHashCode, (JNIEnv* env, jobject, jobject object))
2095 Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2096 return obj->identity_hash();
2097 C2V_END
2098
2099 C2V_VMENTRY_0(jboolean, isInternedString, (JNIEnv* env, jobject, jobject object))
2100 Handle str = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2101 if (!java_lang_String::is_instance(str())) {
2102 return false;
2103 }
2104 int len;
2105 jchar* name = java_lang_String::as_unicode_string(str(), len, CHECK_false);
2106 return (StringTable::lookup(name, len) != nullptr);
2107 C2V_END
2108
2109
2110 C2V_VMENTRY_NULL(jobject, unboxPrimitive, (JNIEnv* env, jobject, jobject object))
2111 if (object == nullptr) {
2112 JVMCI_THROW_NULL(NullPointerException);
2113 }
2114 Handle box = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2115 BasicType type = java_lang_boxing_object::basic_type(box());
2116 jvalue result;
2117 if (java_lang_boxing_object::get_value(box(), &result) == T_ILLEGAL) {
2118 return nullptr;
2119 }
2120 JVMCIObject boxResult = JVMCIENV->create_box(type, &result, JVMCI_CHECK_NULL);
2121 return JVMCIENV->get_jobject(boxResult);
2122 C2V_END
2123
2124 C2V_VMENTRY_NULL(jobject, boxPrimitive, (JNIEnv* env, jobject, jobject object))
2125 if (object == nullptr) {
2126 JVMCI_THROW_NULL(NullPointerException);
2127 }
2128 JVMCIObject box = JVMCIENV->wrap(object);
2129 BasicType type = JVMCIENV->get_box_type(box);
2130 if (type == T_ILLEGAL) {
2131 return nullptr;
2132 }
2133 jvalue value = JVMCIENV->get_boxed_value(type, box);
2134 JavaValue box_result(T_OBJECT);
2135 JavaCallArguments jargs;
2136 Klass* box_klass = nullptr;
2137 Symbol* box_signature = nullptr;
2138 #define BOX_CASE(bt, v, argtype, name) \
2139 case bt: \
2140 jargs.push_##argtype(value.v); \
2141 box_klass = vmClasses::name##_klass(); \
2142 box_signature = vmSymbols::name##_valueOf_signature(); \
2143 break
2144
2145 switch (type) {
2146 BOX_CASE(T_BOOLEAN, z, int, Boolean);
2147 BOX_CASE(T_BYTE, b, int, Byte);
2148 BOX_CASE(T_CHAR, c, int, Character);
2149 BOX_CASE(T_SHORT, s, int, Short);
2150 BOX_CASE(T_INT, i, int, Integer);
2151 BOX_CASE(T_LONG, j, long, Long);
2152 BOX_CASE(T_FLOAT, f, float, Float);
2153 BOX_CASE(T_DOUBLE, d, double, Double);
2154 default:
2155 ShouldNotReachHere();
2156 }
2157 #undef BOX_CASE
2158
2159 JavaCalls::call_static(&box_result,
2160 box_klass,
2161 vmSymbols::valueOf_name(),
2162 box_signature, &jargs, CHECK_NULL);
2163 oop hotspot_box = box_result.get_oop();
2164 JVMCIObject result = JVMCIENV->get_object_constant(hotspot_box, false);
2165 return JVMCIENV->get_jobject(result);
2166 C2V_END
2167
2168 C2V_VMENTRY_NULL(jobjectArray, getDeclaredConstructors, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2169 Klass* klass = UNPACK_PAIR(Klass, klass);
2170 if (klass == nullptr) {
2171 JVMCI_THROW_NULL(NullPointerException);
2172 }
2173 if (!klass->is_instance_klass()) {
2174 JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2175 return JVMCIENV->get_jobjectArray(methods);
2176 }
2177
2178 InstanceKlass* iklass = InstanceKlass::cast(klass);
2179 GrowableArray<Method*> constructors_array;
2180 for (int i = 0; i < iklass->methods()->length(); i++) {
2181 Method* m = iklass->methods()->at(i);
2182 if (m->is_object_initializer()) {
2183 constructors_array.append(m);
2184 }
2185 }
2186 JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(constructors_array.length(), JVMCI_CHECK_NULL);
2187 for (int i = 0; i < constructors_array.length(); i++) {
2188 methodHandle ctor(THREAD, constructors_array.at(i));
2189 JVMCIObject method = JVMCIENV->get_jvmci_method(ctor, JVMCI_CHECK_NULL);
2190 JVMCIENV->put_object_at(methods, i, method);
2191 }
2192 return JVMCIENV->get_jobjectArray(methods);
2193 C2V_END
2194
2195 C2V_VMENTRY_NULL(jobjectArray, getDeclaredMethods, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2196 Klass* klass = UNPACK_PAIR(Klass, klass);
2197 if (klass == nullptr) {
2198 JVMCI_THROW_NULL(NullPointerException);
2199 }
2200 if (!klass->is_instance_klass()) {
2201 JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2202 return JVMCIENV->get_jobjectArray(methods);
2203 }
2204
2205 InstanceKlass* iklass = InstanceKlass::cast(klass);
2206 GrowableArray<Method*> methods_array;
2207 for (int i = 0; i < iklass->methods()->length(); i++) {
2208 Method* m = iklass->methods()->at(i);
2209 if (!m->is_object_initializer() && !m->is_static_initializer() && !m->is_overpass()) {
2210 methods_array.append(m);
2211 }
2212 }
2213 JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(methods_array.length(), JVMCI_CHECK_NULL);
2214 for (int i = 0; i < methods_array.length(); i++) {
2215 methodHandle mh(THREAD, methods_array.at(i));
2216 JVMCIObject method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
2217 JVMCIENV->put_object_at(methods, i, method);
2218 }
2219 return JVMCIENV->get_jobjectArray(methods);
2220 C2V_END
2221
2222 C2V_VMENTRY_NULL(jobjectArray, getDeclaredFieldsInfo, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2223 Klass* klass = UNPACK_PAIR(Klass, klass);
2224 if (klass == nullptr) {
2225 JVMCI_THROW_NULL(NullPointerException);
2226 }
2227 if (!klass->is_instance_klass()) {
2228 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "not an InstanceKlass");
2229 }
2230 InstanceKlass* iklass = InstanceKlass::cast(klass);
2231 int java_fields, injected_fields;
2232 GrowableArray<FieldInfo>* fields = FieldInfoStream::create_FieldInfoArray(iklass->fieldinfo_stream(), &java_fields, &injected_fields);
2233 JVMCIObjectArray array = JVMCIENV->new_FieldInfo_array(fields->length(), JVMCIENV);
2234 for (int i = 0; i < fields->length(); i++) {
2235 JVMCIObject field_info = JVMCIENV->new_FieldInfo(fields->adr_at(i), JVMCI_CHECK_NULL);
2236 JVMCIENV->put_object_at(array, i, field_info);
2237 }
2238 return array.as_jobject();
2239 C2V_END
2240
2241 static jobject read_field_value(Handle obj, long displacement, jchar type_char, bool is_static, Thread* THREAD, JVMCIEnv* JVMCIENV) {
2242
2243 BasicType basic_type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_NULL);
2244 int basic_type_elemsize = type2aelembytes(basic_type);
2245 if (displacement < 0 || ((size_t) displacement + basic_type_elemsize > HeapWordSize * obj->size())) {
2246 // Reading outside of the object bounds
2247 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading outside object bounds");
2248 }
2249
2250 // Perform basic sanity checks on the read. Primitive reads are permitted to read outside the
2251 // bounds of their fields but object reads must map exactly onto the underlying oop slot.
2252 bool aligned = (displacement % basic_type_elemsize) == 0;
2253 if (!aligned) {
2254 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "read is unaligned");
2255 }
2256 if (obj->is_array()) {
2257 // Disallow reading after the last element of an array
2258 size_t array_length = arrayOop(obj())->length();
2259 int lh = obj->klass()->layout_helper();
2260 size_t size_in_bytes = array_length << Klass::layout_helper_log2_element_size(lh);
2261 size_in_bytes += Klass::layout_helper_header_size(lh);
2262 if ((size_t) displacement + basic_type_elemsize > size_in_bytes) {
2263 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading after last array element");
2264 }
2265 }
2266 if (basic_type == T_OBJECT) {
2267 if (obj->is_objArray()) {
2268 if (displacement < arrayOopDesc::base_offset_in_bytes(T_OBJECT)) {
2269 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2270 }
2271 if (((displacement - arrayOopDesc::base_offset_in_bytes(T_OBJECT)) % heapOopSize) != 0) {
2272 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "misaligned object read from array");
2273 }
2274 } else if (obj->is_instance()) {
2275 InstanceKlass* klass = InstanceKlass::cast(is_static ? java_lang_Class::as_Klass(obj()) : obj->klass());
2276 fieldDescriptor fd;
2277 if (!klass->find_field_from_offset(displacement, is_static, &fd)) {
2278 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Can't find field at displacement %d in object of type %s", (int) displacement, klass->external_name()));
2279 }
2280 if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
2281 JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Field at displacement %d in object of type %s is %s but expected %s", (int) displacement,
2282 klass->external_name(), type2name(fd.field_type()), type2name(basic_type)));
2283 }
2284 } else if (obj->is_typeArray()) {
2285 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Can't read objects from primitive array");
2286 } else {
2287 ShouldNotReachHere();
2288 }
2289 } else {
2290 if (obj->is_objArray()) {
2291 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Reading primitive from object array");
2292 } else if (obj->is_typeArray()) {
2293 if (displacement < arrayOopDesc::base_offset_in_bytes(ArrayKlass::cast(obj->klass())->element_type())) {
2294 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2295 }
2296 }
2297 }
2298
2299 jlong value = 0;
2300
2301 // Treat all reads as volatile for simplicity as this function can be used
2302 // both for reading Java fields declared as volatile as well as for constant
2303 // folding Unsafe.get* methods with volatile semantics.
2304
2305 switch (basic_type) {
2306 case T_BOOLEAN: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jboolean>(displacement)); break;
2307 case T_BYTE: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jbyte>(displacement)); break;
2308 case T_SHORT: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jshort>(displacement)); break;
2309 case T_CHAR: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jchar>(displacement)); break;
2310 case T_FLOAT:
2311 case T_INT: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jint>(displacement)); break;
2312 case T_DOUBLE:
2313 case T_LONG: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jlong>(displacement)); break;
2314
2315 case T_OBJECT: {
2316 if (displacement == java_lang_Class::component_mirror_offset() && java_lang_Class::is_instance(obj()) &&
2317 (java_lang_Class::as_Klass(obj()) == nullptr || !java_lang_Class::as_Klass(obj())->is_array_klass())) {
2318 // Class.componentType for non-array classes can transiently contain an int[] that's
2319 // used for locking so always return null to mimic Class.getComponentType()
2320 return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2321 }
2322
2323 // Perform the read including any barriers required to make the reference strongly reachable
2324 // since it will be wrapped as a JavaConstant.
2325 oop value = obj->obj_field_access<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>(displacement);
2326
2327 if (value == nullptr) {
2328 return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2329 } else {
2330 if (value != nullptr && !oopDesc::is_oop(value)) {
2331 // Throw an exception to improve debuggability. This check isn't totally reliable because
2332 // is_oop doesn't try to be completety safe but for most invalid values it provides a good
2333 // enough answer. It possible to crash in the is_oop call but that just means the crash happens
2334 // closer to where things went wrong.
2335 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Read bad oop " INTPTR_FORMAT " at offset " JLONG_FORMAT " in object " INTPTR_FORMAT " of type %s",
2336 p2i(value), displacement, p2i(obj()), obj->klass()->external_name()));
2337 }
2338
2339 JVMCIObject result = JVMCIENV->get_object_constant(value);
2340 return JVMCIENV->get_jobject(result);
2341 }
2342 }
2343
2344 default:
2345 ShouldNotReachHere();
2346 }
2347 JVMCIObject result = JVMCIENV->call_JavaConstant_forPrimitive(type_char, value, JVMCI_CHECK_NULL);
2348 return JVMCIENV->get_jobject(result);
2349 }
2350
2351 C2V_VMENTRY_NULL(jobject, readStaticFieldValue, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), long displacement, jchar type_char))
2352 Klass* klass = UNPACK_PAIR(Klass, klass);
2353 Handle obj(THREAD, klass->java_mirror());
2354 return read_field_value(obj, displacement, type_char, true, THREAD, JVMCIENV);
2355 C2V_END
2356
2357 C2V_VMENTRY_NULL(jobject, readFieldValue, (JNIEnv* env, jobject, jobject object, ARGUMENT_PAIR(expected_type), long displacement, jchar type_char))
2358 if (object == nullptr) {
2359 JVMCI_THROW_NULL(NullPointerException);
2360 }
2361
2362 // asConstant will throw an NPE if a constant contains null
2363 Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2364
2365 Klass* expected_klass = UNPACK_PAIR(Klass, expected_type);
2366 if (expected_klass != nullptr) {
2367 InstanceKlass* expected_iklass = InstanceKlass::cast(expected_klass);
2368 if (!obj->is_a(expected_iklass)) {
2369 // Not of the expected type
2370 return nullptr;
2371 }
2372 }
2373 bool is_static = expected_klass == nullptr && java_lang_Class::is_instance(obj()) && displacement >= InstanceMirrorKlass::offset_of_static_fields();
2374 return read_field_value(obj, displacement, type_char, is_static, THREAD, JVMCIENV);
2375 C2V_END
2376
2377 C2V_VMENTRY_0(jboolean, isInstance, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jobject object))
2378 Klass* klass = UNPACK_PAIR(Klass, klass);
2379 if (object == nullptr || klass == nullptr) {
2380 JVMCI_THROW_0(NullPointerException);
2381 }
2382 Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2383 return obj->is_a(klass);
2384 C2V_END
2385
2386 C2V_VMENTRY_0(jboolean, isAssignableFrom, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(subklass)))
2387 Klass* klass = UNPACK_PAIR(Klass, klass);
2388 Klass* subklass = UNPACK_PAIR(Klass, subklass);
2389 if (klass == nullptr || subklass == nullptr) {
2390 JVMCI_THROW_0(NullPointerException);
2391 }
2392 return subklass->is_subtype_of(klass);
2393 C2V_END
2394
2395 C2V_VMENTRY_0(jboolean, isTrustedForIntrinsics, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2396 Klass* klass = UNPACK_PAIR(Klass, klass);
2397 if (klass == nullptr) {
2398 JVMCI_THROW_0(NullPointerException);
2399 }
2400 InstanceKlass* ik = InstanceKlass::cast(klass);
2401 if (ik->class_loader_data()->is_boot_class_loader_data() || ik->class_loader_data()->is_platform_class_loader_data()) {
2402 return true;
2403 }
2404 return false;
2405 C2V_END
2406
2407 C2V_VMENTRY_NULL(jobject, asJavaType, (JNIEnv* env, jobject, jobject object))
2408 if (object == nullptr) {
2409 JVMCI_THROW_NULL(NullPointerException);
2410 }
2411 Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2412 if (java_lang_Class::is_instance(obj())) {
2413 if (java_lang_Class::is_primitive(obj())) {
2414 JVMCIObject type = JVMCIENV->get_jvmci_primitive_type(java_lang_Class::primitive_type(obj()));
2415 return JVMCIENV->get_jobject(type);
2416 }
2417 Klass* klass = java_lang_Class::as_Klass(obj());
2418 JVMCIKlassHandle klass_handle(THREAD);
2419 klass_handle = klass;
2420 JVMCIObject type = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2421 return JVMCIENV->get_jobject(type);
2422 }
2423 return nullptr;
2424 C2V_END
2425
2426
2427 C2V_VMENTRY_NULL(jobject, asString, (JNIEnv* env, jobject, jobject object))
2428 if (object == nullptr) {
2429 JVMCI_THROW_NULL(NullPointerException);
2430 }
2431 Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2432 const char* str = java_lang_String::as_utf8_string(obj());
2433 JVMCIObject result = JVMCIENV->create_string(str, JVMCI_CHECK_NULL);
2434 return JVMCIENV->get_jobject(result);
2435 C2V_END
2436
2437
2438 C2V_VMENTRY_0(jboolean, equals, (JNIEnv* env, jobject, jobject x, jlong xHandle, jobject y, jlong yHandle))
2439 if (x == nullptr || y == nullptr) {
2440 JVMCI_THROW_0(NullPointerException);
2441 }
2442 return JVMCIENV->resolve_oop_handle(xHandle) == JVMCIENV->resolve_oop_handle(yHandle);
2443 C2V_END
2444
2445 C2V_VMENTRY_NULL(jobject, getJavaMirror, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2446 Klass* klass = UNPACK_PAIR(Klass, klass);
2447 if (klass == nullptr) {
2448 JVMCI_THROW_NULL(NullPointerException);
2449 }
2450 Handle mirror(THREAD, klass->java_mirror());
2451 JVMCIObject result = JVMCIENV->get_object_constant(mirror());
2452 return JVMCIENV->get_jobject(result);
2453 C2V_END
2454
2455
2456 C2V_VMENTRY_0(jint, getArrayLength, (JNIEnv* env, jobject, jobject x))
2457 if (x == nullptr) {
2458 JVMCI_THROW_0(NullPointerException);
2459 }
2460 Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
2461 if (xobj->klass()->is_array_klass()) {
2462 return arrayOop(xobj())->length();
2463 }
2464 return -1;
2465 C2V_END
2466
2467
2468 C2V_VMENTRY_NULL(jobject, readArrayElement, (JNIEnv* env, jobject, jobject x, int index))
2469 if (x == nullptr) {
2470 JVMCI_THROW_NULL(NullPointerException);
2471 }
2472 Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_NULL);
2473 if (xobj->klass()->is_array_klass()) {
2474 arrayOop array = arrayOop(xobj());
2475 BasicType element_type = ArrayKlass::cast(array->klass())->element_type();
2476 if (index < 0 || index >= array->length()) {
2477 return nullptr;
2478 }
2479 JVMCIObject result;
2480
2481 if (element_type == T_OBJECT) {
2482 result = JVMCIENV->get_object_constant(objArrayOop(xobj())->obj_at(index));
2483 if (result.is_null()) {
2484 result = JVMCIENV->get_JavaConstant_NULL_POINTER();
2485 }
2486 } else {
2487 jvalue value;
2488 switch (element_type) {
2489 case T_DOUBLE: value.d = typeArrayOop(xobj())->double_at(index); break;
2490 case T_FLOAT: value.f = typeArrayOop(xobj())->float_at(index); break;
2491 case T_LONG: value.j = typeArrayOop(xobj())->long_at(index); break;
2492 case T_INT: value.i = typeArrayOop(xobj())->int_at(index); break;
2493 case T_SHORT: value.s = typeArrayOop(xobj())->short_at(index); break;
2494 case T_CHAR: value.c = typeArrayOop(xobj())->char_at(index); break;
2495 case T_BYTE: value.b = typeArrayOop(xobj())->byte_at(index); break;
2496 case T_BOOLEAN: value.z = typeArrayOop(xobj())->byte_at(index) & 1; break;
2497 default: ShouldNotReachHere();
2498 }
2499 result = JVMCIENV->create_box(element_type, &value, JVMCI_CHECK_NULL);
2500 }
2501 assert(!result.is_null(), "must have a value");
2502 return JVMCIENV->get_jobject(result);
2503 }
2504 return nullptr;;
2505 C2V_END
2506
2507
2508 C2V_VMENTRY_0(jint, arrayBaseOffset, (JNIEnv* env, jobject, jchar type_char))
2509 BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2510 return arrayOopDesc::base_offset_in_bytes(type);
2511 C2V_END
2512
2513 C2V_VMENTRY_0(jint, arrayIndexScale, (JNIEnv* env, jobject, jchar type_char))
2514 BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2515 return type2aelembytes(type);
2516 C2V_END
2517
2518 C2V_VMENTRY(void, clearOopHandle, (JNIEnv* env, jobject, jlong oop_handle))
2519 if (oop_handle == 0L) {
2520 JVMCI_THROW(NullPointerException);
2521 }
2522 // Assert before nulling out, for better debugging.
2523 assert(JVMCIRuntime::is_oop_handle(oop_handle), "precondition");
2524 oop* oop_ptr = (oop*) oop_handle;
2525 NativeAccess<>::oop_store(oop_ptr, (oop) nullptr);
2526 C2V_END
2527
2528 C2V_VMENTRY(void, releaseClearedOopHandles, (JNIEnv* env, jobject))
2529 JVMCIENV->runtime()->release_cleared_oop_handles();
2530 C2V_END
2531
2532 static void requireJVMCINativeLibrary(JVMCI_TRAPS) {
2533 if (!UseJVMCINativeLibrary) {
2534 JVMCI_THROW_MSG(UnsupportedOperationException, "JVMCI shared library is not enabled (requires -XX:+UseJVMCINativeLibrary)");
2535 }
2536 }
2537
2538 C2V_VMENTRY_NULL(jlongArray, registerNativeMethods, (JNIEnv* env, jobject, jclass mirror))
2539 requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2540 requireInHotSpot("registerNativeMethods", JVMCI_CHECK_NULL);
2541 char* sl_path;
2542 void* sl_handle;
2543 JVMCIRuntime* runtime;
2544 {
2545 // Ensure the JVMCI shared library runtime is initialized.
2546 PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2547 PEER_JVMCIENV->check_init(JVMCI_CHECK_NULL);
2548
2549 HandleMark hm(THREAD);
2550 runtime = JVMCI::compiler_runtime(thread);
2551 if (PEER_JVMCIENV->has_pending_exception()) {
2552 PEER_JVMCIENV->describe_pending_exception(tty);
2553 }
2554 sl_handle = JVMCI::get_shared_library(sl_path, false);
2555 if (sl_handle == nullptr) {
2556 JVMCI_THROW_MSG_NULL(InternalError, err_msg("Error initializing JVMCI runtime %d", runtime->id()));
2557 }
2558 }
2559
2560 if (mirror == nullptr) {
2561 JVMCI_THROW_NULL(NullPointerException);
2562 }
2563 Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2564 if (klass == nullptr || !klass->is_instance_klass()) {
2565 JVMCI_THROW_MSG_NULL(IllegalArgumentException, "clazz is for primitive type");
2566 }
2567
2568 InstanceKlass* iklass = InstanceKlass::cast(klass);
2569 for (int i = 0; i < iklass->methods()->length(); i++) {
2570 methodHandle method(THREAD, iklass->methods()->at(i));
2571 if (method->is_native()) {
2572
2573 // Compute argument size
2574 int args_size = 1 // JNIEnv
2575 + (method->is_static() ? 1 : 0) // class for static methods
2576 + method->size_of_parameters(); // actual parameters
2577
2578 // 1) Try JNI short style
2579 stringStream st;
2580 char* pure_name = NativeLookup::pure_jni_name(method);
2581 guarantee(pure_name != nullptr, "Illegal native method name encountered");
2582 st.print_raw(pure_name);
2583 char* jni_name = st.as_string();
2584
2585 address entry = (address) os::dll_lookup(sl_handle, jni_name);
2586 if (entry == nullptr) {
2587 // 2) Try JNI long style
2588 st.reset();
2589 char* long_name = NativeLookup::long_jni_name(method);
2590 guarantee(long_name != nullptr, "Illegal native method name encountered");
2591 st.print_raw(pure_name);
2592 st.print_raw(long_name);
2593 char* jni_long_name = st.as_string();
2594 entry = (address) os::dll_lookup(sl_handle, jni_long_name);
2595 if (entry == nullptr) {
2596 JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [neither %s nor %s exist in %s]",
2597 method->name_and_sig_as_C_string(),
2598 jni_name, jni_long_name, sl_path));
2599 }
2600 }
2601
2602 if (method->has_native_function() && entry != method->native_function()) {
2603 JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [cannot re-link from " PTR_FORMAT " to " PTR_FORMAT "]",
2604 method->name_and_sig_as_C_string(), p2i(method->native_function()), p2i(entry)));
2605 }
2606 method->set_native_function(entry, Method::native_bind_event_is_interesting);
2607 log_debug(jni, resolve)("[Dynamic-linking native method %s.%s ... JNI] @ " PTR_FORMAT,
2608 method->method_holder()->external_name(),
2609 method->name()->as_C_string(),
2610 p2i((void*) entry));
2611 }
2612 }
2613
2614 typeArrayOop info_oop = oopFactory::new_longArray(4, CHECK_NULL);
2615 jlongArray info = (jlongArray) JNIHandles::make_local(THREAD, info_oop);
2616 runtime->init_JavaVM_info(info, JVMCI_CHECK_NULL);
2617 return info;
2618 C2V_END
2619
2620 C2V_VMENTRY_PREFIX(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject c2vm))
2621 if (thread == nullptr || thread->libjvmci_runtime() == nullptr) {
2622 // Called from unattached JVMCI shared library thread
2623 return false;
2624 }
2625 if (thread->jni_environment() == env) {
2626 C2V_BLOCK(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject))
2627 JVMCITraceMark jtm("isCurrentThreadAttached");
2628 requireJVMCINativeLibrary(JVMCI_CHECK_0);
2629 JVMCIRuntime* runtime = thread->libjvmci_runtime();
2630 if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2631 JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in isCurrentThreadAttached");
2632 }
2633 JNIEnv* peerEnv;
2634 return runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) == JNI_OK;
2635 }
2636 return true;
2637 C2V_END
2638
2639 C2V_VMENTRY_PREFIX(jlong, getCurrentJavaThread, (JNIEnv* env, jobject c2vm))
2640 if (thread == nullptr) {
2641 // Called from unattached JVMCI shared library thread
2642 return 0L;
2643 }
2644 return (jlong) p2i(thread);
2645 C2V_END
2646
2647 // Attaches a thread started in a JVMCI shared library to a JavaThread and JVMCI runtime.
2648 static void attachSharedLibraryThread(JNIEnv* env, jbyteArray name, jboolean as_daemon) {
2649 JavaVM* javaVM = nullptr;
2650 jint res = env->GetJavaVM(&javaVM);
2651 if (res != JNI_OK) {
2652 JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Error getting shared library JavaVM from shared library JNIEnv: %d", res));
2653 }
2654 extern struct JavaVM_ main_vm;
2655 JNIEnv* hotspotEnv;
2656
2657 int name_len = env->GetArrayLength(name);
2658 char name_buf[64]; // Cannot use Resource heap as it requires a current thread
2659 int to_copy = MIN2(name_len, (int) sizeof(name_buf) - 1);
2660 env->GetByteArrayRegion(name, 0, to_copy, (jbyte*) name_buf);
2661 name_buf[to_copy] = '\0';
2662 JavaVMAttachArgs attach_args;
2663 attach_args.version = JNI_VERSION_1_2;
2664 attach_args.name = name_buf;
2665 attach_args.group = nullptr;
2666 res = as_daemon ? main_vm.AttachCurrentThreadAsDaemon((void**)&hotspotEnv, &attach_args) :
2667 main_vm.AttachCurrentThread((void**)&hotspotEnv, &attach_args);
2668 if (res != JNI_OK) {
2669 JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Trying to attach thread returned %d", res));
2670 }
2671 JavaThread* thread = JavaThread::thread_from_jni_environment(hotspotEnv);
2672 const char* attach_error;
2673 {
2674 // Transition to VM
2675 JVMCI_VM_ENTRY_MARK
2676 attach_error = JVMCIRuntime::attach_shared_library_thread(thread, javaVM);
2677 // Transition back to Native
2678 }
2679 if (attach_error != nullptr) {
2680 JNI_THROW("attachCurrentThread", InternalError, attach_error);
2681 }
2682 }
2683
2684 C2V_VMENTRY_PREFIX(jboolean, attachCurrentThread, (JNIEnv* env, jobject c2vm, jbyteArray name, jboolean as_daemon, jlongArray javaVM_info))
2685 if (thread == nullptr) {
2686 attachSharedLibraryThread(env, name, as_daemon);
2687 return true;
2688 }
2689 if (thread->jni_environment() == env) {
2690 // Called from HotSpot
2691 C2V_BLOCK(jboolean, attachCurrentThread, (JNIEnv* env, jobject, jboolean))
2692 JVMCITraceMark jtm("attachCurrentThread");
2693 requireJVMCINativeLibrary(JVMCI_CHECK_0);
2694
2695 JVMCIRuntime* runtime = JVMCI::compiler_runtime(thread);
2696 JNIEnv* peerJNIEnv;
2697 if (runtime->has_shared_library_javavm()) {
2698 if (runtime->GetEnv(thread, (void**)&peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2699 // Already attached
2700 runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2701 return false;
2702 }
2703 }
2704
2705 {
2706 // Ensure the JVMCI shared library runtime is initialized.
2707 PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2708 PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2709
2710 HandleMark hm(thread);
2711 JVMCIObject receiver = runtime->get_HotSpotJVMCIRuntime(PEER_JVMCIENV);
2712 if (PEER_JVMCIENV->has_pending_exception()) {
2713 PEER_JVMCIENV->describe_pending_exception(tty);
2714 }
2715 char* sl_path;
2716 if (JVMCI::get_shared_library(sl_path, false) == nullptr) {
2717 JVMCI_THROW_MSG_0(InternalError, "Error initializing JVMCI runtime");
2718 }
2719 }
2720
2721 JavaVMAttachArgs attach_args;
2722 attach_args.version = JNI_VERSION_1_2;
2723 attach_args.name = const_cast<char*>(thread->name());
2724 attach_args.group = nullptr;
2725 if (runtime->GetEnv(thread, (void**) &peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2726 return false;
2727 }
2728 jint res = as_daemon ? runtime->AttachCurrentThreadAsDaemon(thread, (void**) &peerJNIEnv, &attach_args) :
2729 runtime->AttachCurrentThread(thread, (void**) &peerJNIEnv, &attach_args);
2730
2731 if (res == JNI_OK) {
2732 guarantee(peerJNIEnv != nullptr, "must be");
2733 runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2734 JVMCI_event_1("attached to JavaVM[" JLONG_FORMAT "] for JVMCI runtime %d", runtime->get_shared_library_javavm_id(), runtime->id());
2735 return true;
2736 }
2737 JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, attach_args.name));
2738 }
2739 // Called from JVMCI shared library
2740 return false;
2741 C2V_END
2742
2743 C2V_VMENTRY_PREFIX(jboolean, detachCurrentThread, (JNIEnv* env, jobject c2vm, jboolean release))
2744 if (thread == nullptr) {
2745 // Called from unattached JVMCI shared library thread
2746 JNI_THROW_("detachCurrentThread", IllegalStateException, "Cannot detach non-attached thread", false);
2747 }
2748 if (thread->jni_environment() == env) {
2749 // Called from HotSpot
2750 C2V_BLOCK(void, detachCurrentThread, (JNIEnv* env, jobject))
2751 JVMCITraceMark jtm("detachCurrentThread");
2752 requireJVMCINativeLibrary(JVMCI_CHECK_0);
2753 requireInHotSpot("detachCurrentThread", JVMCI_CHECK_0);
2754 JVMCIRuntime* runtime = thread->libjvmci_runtime();
2755 if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2756 JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in detachCurrentThread");
2757 }
2758 JNIEnv* peerEnv;
2759
2760 if (runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) != JNI_OK) {
2761 JVMCI_THROW_MSG_0(IllegalStateException, err_msg("Cannot detach non-attached thread: %s", thread->name()));
2762 }
2763 jint res = runtime->DetachCurrentThread(thread);
2764 if (res != JNI_OK) {
2765 JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, thread->name()));
2766 }
2767 JVMCI_event_1("detached from JavaVM[" JLONG_FORMAT "] for JVMCI runtime %d",
2768 runtime->get_shared_library_javavm_id(), runtime->id());
2769 if (release) {
2770 return runtime->detach_thread(thread, "user thread detach");
2771 }
2772 } else {
2773 // Called from attached JVMCI shared library thread
2774 if (release) {
2775 JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread cannot release JVMCI shared library JavaVM", false);
2776 }
2777 JVMCIRuntime* runtime = thread->libjvmci_runtime();
2778 if (runtime == nullptr) {
2779 JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread should have a JVMCI runtime", false);
2780 }
2781 {
2782 // Transition to VM
2783 C2V_BLOCK(jboolean, detachCurrentThread, (JNIEnv* env, jobject))
2784 // Cannot destroy shared library JavaVM as we're about to return to it.
2785 runtime->detach_thread(thread, "shared library thread detach", false);
2786 JVMCI_event_1("detaching JVMCI shared library thread from HotSpot JavaVM");
2787 // Transition back to Native
2788 }
2789 extern struct JavaVM_ main_vm;
2790 jint res = main_vm.DetachCurrentThread();
2791 if (res != JNI_OK) {
2792 JNI_THROW_("detachCurrentThread", InternalError, "Cannot detach non-attached thread", false);
2793 }
2794 }
2795 return false;
2796 C2V_END
2797
2798 C2V_VMENTRY_0(jlong, translate, (JNIEnv* env, jobject, jobject obj_handle, jboolean callPostTranslation))
2799 requireJVMCINativeLibrary(JVMCI_CHECK_0);
2800 if (obj_handle == nullptr) {
2801 return 0L;
2802 }
2803 PEER_JVMCIENV_FROM_THREAD(THREAD, !JVMCIENV->is_hotspot());
2804 CompilerThreadCanCallJava canCallJava(thread, PEER_JVMCIENV->is_hotspot());
2805 PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2806
2807 JVMCIEnv* thisEnv = JVMCIENV;
2808 JVMCIObject obj = thisEnv->wrap(obj_handle);
2809 JVMCIObject result;
2810 if (thisEnv->isa_HotSpotResolvedJavaMethodImpl(obj)) {
2811 methodHandle method(THREAD, thisEnv->asMethod(obj));
2812 result = PEER_JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_0);
2813 } else if (thisEnv->isa_HotSpotResolvedObjectTypeImpl(obj)) {
2814 Klass* klass = thisEnv->asKlass(obj);
2815 JVMCIKlassHandle klass_handle(THREAD);
2816 klass_handle = klass;
2817 result = PEER_JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_0);
2818 } else if (thisEnv->isa_HotSpotResolvedPrimitiveType(obj)) {
2819 BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(obj), JVMCI_CHECK_0);
2820 result = PEER_JVMCIENV->get_jvmci_primitive_type(type);
2821 } else if (thisEnv->isa_IndirectHotSpotObjectConstantImpl(obj) ||
2822 thisEnv->isa_DirectHotSpotObjectConstantImpl(obj)) {
2823 Handle constant = thisEnv->asConstant(obj, JVMCI_CHECK_0);
2824 result = PEER_JVMCIENV->get_object_constant(constant());
2825 } else if (thisEnv->isa_HotSpotNmethod(obj)) {
2826 if (PEER_JVMCIENV->is_hotspot()) {
2827 JVMCINMethodHandle nmethod_handle(THREAD);
2828 nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2829 if (nm != nullptr) {
2830 JVMCINMethodData* data = nm->jvmci_nmethod_data();
2831 if (data != nullptr) {
2832 // Only the mirror in the HotSpot heap is accessible
2833 // through JVMCINMethodData
2834 oop nmethod_mirror = data->get_nmethod_mirror(nm, /* phantom_ref */ true);
2835 if (nmethod_mirror != nullptr) {
2836 result = HotSpotJVMCI::wrap(nmethod_mirror);
2837 }
2838 }
2839 }
2840 }
2841
2842 if (result.is_null()) {
2843 JVMCIObject methodObject = thisEnv->get_HotSpotNmethod_method(obj);
2844 methodHandle mh(THREAD, thisEnv->asMethod(methodObject));
2845 jboolean isDefault = thisEnv->get_HotSpotNmethod_isDefault(obj);
2846 jlong compileIdSnapshot = thisEnv->get_HotSpotNmethod_compileIdSnapshot(obj);
2847 JVMCIObject name_string = thisEnv->get_InstalledCode_name(obj);
2848 const char* cstring = name_string.is_null() ? nullptr : thisEnv->as_utf8_string(name_string);
2849 // Create a new HotSpotNmethod instance in the peer runtime
2850 result = PEER_JVMCIENV->new_HotSpotNmethod(mh, cstring, isDefault, compileIdSnapshot, JVMCI_CHECK_0);
2851 JVMCINMethodHandle nmethod_handle(THREAD);
2852 nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2853 if (result.is_null()) {
2854 // exception occurred (e.g. OOME) creating a new HotSpotNmethod
2855 } else if (nm == nullptr) {
2856 // nmethod must have been unloaded
2857 } else {
2858 // Link the new HotSpotNmethod to the nmethod
2859 PEER_JVMCIENV->initialize_installed_code(result, nm, JVMCI_CHECK_0);
2860 // Only non-default HotSpotNmethod instances in the HotSpot heap are tracked directly by the runtime.
2861 if (!isDefault && PEER_JVMCIENV->is_hotspot()) {
2862 JVMCINMethodData* data = nm->jvmci_nmethod_data();
2863 if (data == nullptr) {
2864 JVMCI_THROW_MSG_0(IllegalArgumentException, "Missing HotSpotNmethod data");
2865 }
2866 if (data->get_nmethod_mirror(nm, /* phantom_ref */ false) != nullptr) {
2867 JVMCI_THROW_MSG_0(IllegalArgumentException, "Cannot overwrite existing HotSpotNmethod mirror for nmethod");
2868 }
2869 oop nmethod_mirror = HotSpotJVMCI::resolve(result);
2870 data->set_nmethod_mirror(nm, nmethod_mirror);
2871 }
2872 }
2873 }
2874 } else {
2875 JVMCI_THROW_MSG_0(IllegalArgumentException,
2876 err_msg("Cannot translate object of type: %s", thisEnv->klass_name(obj)));
2877 }
2878 if (callPostTranslation) {
2879 PEER_JVMCIENV->call_HotSpotJVMCIRuntime_postTranslation(result, JVMCI_CHECK_0);
2880 }
2881 // Propagate any exception that occurred while creating the translated object
2882 if (PEER_JVMCIENV->transfer_pending_exception(thread, thisEnv)) {
2883 return 0L;
2884 }
2885 return (jlong) PEER_JVMCIENV->make_global(result).as_jobject();
2886 C2V_END
2887
2888 C2V_VMENTRY_NULL(jobject, unhand, (JNIEnv* env, jobject, jlong obj_handle))
2889 requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2890 if (obj_handle == 0L) {
2891 return nullptr;
2892 }
2893 jobject global_handle = (jobject) obj_handle;
2894 JVMCIObject global_handle_obj = JVMCIENV->wrap(global_handle);
2895 jobject result = JVMCIENV->make_local(global_handle_obj).as_jobject();
2896
2897 JVMCIENV->destroy_global(global_handle_obj);
2898 return result;
2899 C2V_END
2900
2901 C2V_VMENTRY(void, updateHotSpotNmethod, (JNIEnv* env, jobject, jobject code_handle))
2902 JVMCIObject code = JVMCIENV->wrap(code_handle);
2903 // Execute this operation for the side effect of updating the InstalledCode state
2904 JVMCINMethodHandle nmethod_handle(THREAD);
2905 JVMCIENV->get_nmethod(code, nmethod_handle);
2906 C2V_END
2907
2908 C2V_VMENTRY_NULL(jbyteArray, getCode, (JNIEnv* env, jobject, jobject code_handle))
2909 JVMCIObject code = JVMCIENV->wrap(code_handle);
2910 CodeBlob* cb = JVMCIENV->get_code_blob(code);
2911 if (cb == nullptr) {
2912 return nullptr;
2913 }
2914 // Make a resource copy of code before the allocation causes a safepoint
2915 int code_size = cb->code_size();
2916 jbyte* code_bytes = NEW_RESOURCE_ARRAY(jbyte, code_size);
2917 memcpy(code_bytes, (jbyte*) cb->code_begin(), code_size);
2918
2919 JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
2920 JVMCIENV->copy_bytes_from(code_bytes, result, 0, code_size);
2921 return JVMCIENV->get_jbyteArray(result);
2922 C2V_END
2923
2924 C2V_VMENTRY_NULL(jobject, asReflectionExecutable, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
2925 requireInHotSpot("asReflectionExecutable", JVMCI_CHECK_NULL);
2926 methodHandle m(THREAD, UNPACK_PAIR(Method, method));
2927 oop executable;
2928 if (m->is_object_initializer()) {
2929 executable = Reflection::new_constructor(m, CHECK_NULL);
2930 } else if (m->is_static_initializer()) {
2931 JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2932 "Cannot create java.lang.reflect.Method for class initializer");
2933 } else {
2934 executable = Reflection::new_method(m, false, CHECK_NULL);
2935 }
2936 return JNIHandles::make_local(THREAD, executable);
2937 C2V_END
2938
2939 static InstanceKlass* check_field(Klass* klass, jint index, JVMCI_TRAPS) {
2940 if (!klass->is_instance_klass()) {
2941 JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2942 err_msg("Expected non-primitive type, got %s", klass->external_name()));
2943 }
2944 InstanceKlass* iklass = InstanceKlass::cast(klass);
2945 if (index < 0 || index > iklass->total_fields_count()) {
2946 JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2947 err_msg("Field index %d out of bounds for %s", index, klass->external_name()));
2948 }
2949 return iklass;
2950 }
2951
2952 C2V_VMENTRY_NULL(jobject, asReflectionField, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index))
2953 requireInHotSpot("asReflectionField", JVMCI_CHECK_NULL);
2954 Klass* klass = UNPACK_PAIR(Klass, klass);
2955 InstanceKlass* iklass = check_field(klass, index, JVMCIENV);
2956 fieldDescriptor fd(iklass, index);
2957 oop reflected = Reflection::new_field(&fd, CHECK_NULL);
2958 return JNIHandles::make_local(THREAD, reflected);
2959 C2V_END
2960
2961 static jbyteArray get_encoded_annotation_data(InstanceKlass* holder, AnnotationArray* annotations_array, bool for_class,
2962 jint filter_length, jlong filter_klass_pointers,
2963 JavaThread* THREAD, JVMCIEnv* JVMCIENV) {
2964 // Get a ConstantPool object for annotation parsing
2965 Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
2966 reflect_ConstantPool::set_cp(jcp(), holder->constants());
2967
2968 // load VMSupport
2969 Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
2970 Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK_NULL);
2971
2972 InstanceKlass* vm_support = InstanceKlass::cast(k);
2973 if (vm_support->should_be_initialized()) {
2974 vm_support->initialize(CHECK_NULL);
2975 }
2976
2977 typeArrayOop annotations_oop = Annotations::make_java_array(annotations_array, CHECK_NULL);
2978 typeArrayHandle annotations = typeArrayHandle(THREAD, annotations_oop);
2979
2980 InstanceKlass** filter = filter_length == 1 ?
2981 (InstanceKlass**) &filter_klass_pointers:
2982 (InstanceKlass**) filter_klass_pointers;
2983 objArrayOop filter_oop = oopFactory::new_objArray(vmClasses::Class_klass(), filter_length, CHECK_NULL);
2984 objArrayHandle filter_classes(THREAD, filter_oop);
2985 for (int i = 0; i < filter_length; i++) {
2986 filter_classes->obj_at_put(i, filter[i]->java_mirror());
2987 }
2988
2989 // invoke VMSupport.encodeAnnotations
2990 JavaValue result(T_OBJECT);
2991 JavaCallArguments args;
2992 args.push_oop(annotations);
2993 args.push_oop(Handle(THREAD, holder->java_mirror()));
2994 args.push_oop(jcp);
2995 args.push_int(for_class);
2996 args.push_oop(filter_classes);
2997 Symbol* signature = vmSymbols::encodeAnnotations_signature();
2998 JavaCalls::call_static(&result,
2999 vm_support,
3000 vmSymbols::encodeAnnotations_name(),
3001 signature,
3002 &args,
3003 CHECK_NULL);
3004
3005 oop res = result.get_oop();
3006 if (JVMCIENV->is_hotspot()) {
3007 return (jbyteArray) JNIHandles::make_local(THREAD, res);
3008 }
3009
3010 typeArrayOop ba = typeArrayOop(res);
3011 int ba_len = ba->length();
3012 jbyte* ba_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jbyte, ba_len);
3013 if (ba_buf == nullptr) {
3014 JVMCI_THROW_MSG_NULL(InternalError,
3015 err_msg("could not allocate %d bytes", ba_len));
3016
3017 }
3018 memcpy(ba_buf, ba->byte_at_addr(0), ba_len);
3019 JVMCIPrimitiveArray ba_dest = JVMCIENV->new_byteArray(ba_len, JVMCI_CHECK_NULL);
3020 JVMCIENV->copy_bytes_from(ba_buf, ba_dest, 0, ba_len);
3021 return JVMCIENV->get_jbyteArray(ba_dest);
3022 }
3023
3024 C2V_VMENTRY_NULL(jbyteArray, getEncodedClassAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass),
3025 jobject filter, jint filter_length, jlong filter_klass_pointers))
3026 CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3027 InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
3028 return get_encoded_annotation_data(holder, holder->class_annotations(), true, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3029 C2V_END
3030
3031 C2V_VMENTRY_NULL(jbyteArray, getEncodedExecutableAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3032 jobject filter, jint filter_length, jlong filter_klass_pointers))
3033 CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3034 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3035 return get_encoded_annotation_data(method->method_holder(), method->annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3036 C2V_END
3037
3038 C2V_VMENTRY_NULL(jbyteArray, getEncodedFieldAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index,
3039 jobject filter, jint filter_length, jlong filter_klass_pointers))
3040 CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3041 InstanceKlass* holder = check_field(InstanceKlass::cast(UNPACK_PAIR(Klass, klass)), index, JVMCIENV);
3042 fieldDescriptor fd(holder, index);
3043 return get_encoded_annotation_data(holder, fd.annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3044 C2V_END
3045
3046 C2V_VMENTRY_NULL(jobjectArray, getFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address, jobjectArray current))
3047 FailedSpeculation* head = *((FailedSpeculation**)(address) failed_speculations_address);
3048 int result_length = 0;
3049 for (FailedSpeculation* fs = head; fs != nullptr; fs = fs->next()) {
3050 result_length++;
3051 }
3052 int current_length = 0;
3053 JVMCIObjectArray current_array = nullptr;
3054 if (current != nullptr) {
3055 current_array = JVMCIENV->wrap(current);
3056 current_length = JVMCIENV->get_length(current_array);
3057 if (current_length == result_length) {
3058 // No new failures
3059 return current;
3060 }
3061 }
3062 JVMCIObjectArray result = JVMCIENV->new_byte_array_array(result_length, JVMCI_CHECK_NULL);
3063 int result_index = 0;
3064 for (FailedSpeculation* fs = head; result_index < result_length; fs = fs->next()) {
3065 assert(fs != nullptr, "npe");
3066 JVMCIPrimitiveArray entry;
3067 if (result_index < current_length) {
3068 entry = (JVMCIPrimitiveArray) JVMCIENV->get_object_at(current_array, result_index);
3069 } else {
3070 entry = JVMCIENV->new_byteArray(fs->data_len(), JVMCI_CHECK_NULL);
3071 JVMCIENV->copy_bytes_from((jbyte*) fs->data(), entry, 0, fs->data_len());
3072 }
3073 JVMCIENV->put_object_at(result, result_index++, entry);
3074 }
3075 return JVMCIENV->get_jobjectArray(result);
3076 C2V_END
3077
3078 C2V_VMENTRY_0(jlong, getFailedSpeculationsAddress, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
3079 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3080 MethodData* method_data = get_profiling_method_data(method, CHECK_0);
3081 return (jlong) method_data->get_failed_speculations_address();
3082 C2V_END
3083
3084 C2V_VMENTRY(void, releaseFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address))
3085 FailedSpeculation::free_failed_speculations((FailedSpeculation**)(address) failed_speculations_address);
3086 C2V_END
3087
3088 C2V_VMENTRY_0(jboolean, addFailedSpeculation, (JNIEnv* env, jobject, jlong failed_speculations_address, jbyteArray speculation_obj))
3089 JVMCIPrimitiveArray speculation_handle = JVMCIENV->wrap(speculation_obj);
3090 int speculation_len = JVMCIENV->get_length(speculation_handle);
3091 char* speculation = NEW_RESOURCE_ARRAY(char, speculation_len);
3092 JVMCIENV->copy_bytes_to(speculation_handle, (jbyte*) speculation, 0, speculation_len);
3093 return FailedSpeculation::add_failed_speculation(nullptr, (FailedSpeculation**)(address) failed_speculations_address, (address) speculation, speculation_len);
3094 C2V_END
3095
3096 C2V_VMENTRY(void, callSystemExit, (JNIEnv* env, jobject, jint status))
3097 if (!JVMCIENV->is_hotspot()) {
3098 // It's generally not safe to call Java code before the module system is initialized
3099 if (!Universe::is_module_initialized()) {
3100 JVMCI_event_1("callSystemExit(%d) before Universe::is_module_initialized() -> direct VM exit", status);
3101 vm_exit_during_initialization();
3102 }
3103 }
3104 CompilerThreadCanCallJava canCallJava(thread, true);
3105 JavaValue result(T_VOID);
3106 JavaCallArguments jargs(1);
3107 jargs.push_int(status);
3108 JavaCalls::call_static(&result,
3109 vmClasses::System_klass(),
3110 vmSymbols::exit_method_name(),
3111 vmSymbols::int_void_signature(),
3112 &jargs,
3113 CHECK);
3114 C2V_END
3115
3116 C2V_VMENTRY_0(jlong, ticksNow, (JNIEnv* env, jobject))
3117 return CompilerEvent::ticksNow();
3118 C2V_END
3119
3120 C2V_VMENTRY_0(jint, registerCompilerPhase, (JNIEnv* env, jobject, jstring jphase_name))
3121 #if INCLUDE_JFR
3122 JVMCIObject phase_name = JVMCIENV->wrap(jphase_name);
3123 const char *name = JVMCIENV->as_utf8_string(phase_name);
3124 return CompilerEvent::PhaseEvent::get_phase_id(name, true, true, true);
3125 #else
3126 return -1;
3127 #endif // !INCLUDE_JFR
3128 C2V_END
3129
3130 C2V_VMENTRY(void, notifyCompilerPhaseEvent, (JNIEnv* env, jobject, jlong startTime, jint phase, jint compileId, jint level))
3131 EventCompilerPhase event(UNTIMED);
3132 if (event.should_commit()) {
3133 CompilerEvent::PhaseEvent::post(event, startTime, phase, compileId, level);
3134 }
3135 C2V_END
3136
3137 C2V_VMENTRY(void, notifyCompilerInliningEvent, (JNIEnv* env, jobject, jint compileId, ARGUMENT_PAIR(caller), ARGUMENT_PAIR(callee), jboolean succeeded, jstring jmessage, jint bci))
3138 EventCompilerInlining event;
3139 if (event.should_commit()) {
3140 Method* caller = UNPACK_PAIR(Method, caller);
3141 Method* callee = UNPACK_PAIR(Method, callee);
3142 JVMCIObject message = JVMCIENV->wrap(jmessage);
3143 CompilerEvent::InlineEvent::post(event, compileId, caller, callee, succeeded, JVMCIENV->as_utf8_string(message), bci);
3144 }
3145 C2V_END
3146
3147 C2V_VMENTRY(void, setThreadLocalObject, (JNIEnv* env, jobject, jint id, jobject value))
3148 requireInHotSpot("setThreadLocalObject", JVMCI_CHECK);
3149 if (id == 0) {
3150 thread->set_jvmci_reserved_oop0(JNIHandles::resolve(value));
3151 return;
3152 }
3153 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3154 err_msg("%d is not a valid thread local id", id));
3155 C2V_END
3156
3157 C2V_VMENTRY_NULL(jobject, getThreadLocalObject, (JNIEnv* env, jobject, jint id))
3158 requireInHotSpot("getThreadLocalObject", JVMCI_CHECK_NULL);
3159 if (id == 0) {
3160 return JNIHandles::make_local(thread->get_jvmci_reserved_oop0());
3161 }
3162 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
3163 err_msg("%d is not a valid thread local id", id));
3164 C2V_END
3165
3166 C2V_VMENTRY(void, setThreadLocalLong, (JNIEnv* env, jobject, jint id, jlong value))
3167 requireInHotSpot("setThreadLocalLong", JVMCI_CHECK);
3168 if (id == 0) {
3169 thread->set_jvmci_reserved0(value);
3170 } else if (id == 1) {
3171 thread->set_jvmci_reserved1(value);
3172 } else {
3173 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3174 err_msg("%d is not a valid thread local id", id));
3175 }
3176 C2V_END
3177
3178 C2V_VMENTRY_0(jlong, getThreadLocalLong, (JNIEnv* env, jobject, jint id))
3179 requireInHotSpot("getThreadLocalLong", JVMCI_CHECK_0);
3180 if (id == 0) {
3181 return thread->get_jvmci_reserved0();
3182 } else if (id == 1) {
3183 return thread->get_jvmci_reserved1();
3184 } else {
3185 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
3186 err_msg("%d is not a valid thread local id", id));
3187 }
3188 C2V_END
3189
3190 C2V_VMENTRY(void, getOopMapAt, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3191 jint bci, jlongArray oop_map_handle))
3192 methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3193 if (bci < 0 || bci >= method->code_size()) {
3194 JVMCI_THROW_MSG(IllegalArgumentException,
3195 err_msg("bci %d is out of bounds [0 .. %d)", bci, method->code_size()));
3196 }
3197 InterpreterOopMap mask;
3198 OopMapCache::compute_one_oop_map(method, bci, &mask);
3199 if (!mask.has_valid_mask()) {
3200 JVMCI_THROW_MSG(IllegalArgumentException, err_msg("bci %d is not valid", bci));
3201 }
3202 if (mask.number_of_entries() == 0) {
3203 return;
3204 }
3205
3206 int nslots = method->max_locals() + method->max_stack();
3207 int nwords = ((nslots - 1) / 64) + 1;
3208 JVMCIPrimitiveArray oop_map = JVMCIENV->wrap(oop_map_handle);
3209 int oop_map_len = JVMCIENV->get_length(oop_map);
3210 if (nwords > oop_map_len) {
3211 JVMCI_THROW_MSG(IllegalArgumentException,
3212 err_msg("oop map too short: %d > %d", nwords, oop_map_len));
3213 }
3214
3215 jlong* oop_map_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jlong, nwords);
3216 if (oop_map_buf == nullptr) {
3217 JVMCI_THROW_MSG(InternalError, err_msg("could not allocate %d longs", nwords));
3218 }
3219 for (int i = 0; i < nwords; i++) {
3220 oop_map_buf[i] = 0L;
3221 }
3222
3223 BitMapView oop_map_view = BitMapView((BitMap::bm_word_t*) oop_map_buf, nwords * BitsPerLong);
3224 for (int i = 0; i < nslots; i++) {
3225 if (mask.is_oop(i)) {
3226 oop_map_view.set_bit(i);
3227 }
3228 }
3229 JVMCIENV->copy_longs_from((jlong*)oop_map_buf, oop_map, 0, nwords);
3230 C2V_END
3231
3232 C2V_VMENTRY_0(jint, getCompilationActivityMode, (JNIEnv* env, jobject))
3233 return CompileBroker::get_compilation_activity_mode();
3234 C2V_END
3235
3236 C2V_VMENTRY_0(jboolean, isCompilerThread, (JNIEnv* env, jobject))
3237 return thread->is_Compiler_thread();
3238 C2V_END
3239
3240 #define CC (char*) /*cast a literal from (const char*)*/
3241 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
3242
3243 #define STRING "Ljava/lang/String;"
3244 #define OBJECT "Ljava/lang/Object;"
3245 #define CLASS "Ljava/lang/Class;"
3246 #define OBJECTCONSTANT "Ljdk/vm/ci/hotspot/HotSpotObjectConstantImpl;"
3247 #define EXECUTABLE "Ljava/lang/reflect/Executable;"
3248 #define STACK_TRACE_ELEMENT "Ljava/lang/StackTraceElement;"
3249 #define INSTALLED_CODE "Ljdk/vm/ci/code/InstalledCode;"
3250 #define BYTECODE_FRAME "Ljdk/vm/ci/code/BytecodeFrame;"
3251 #define JAVACONSTANT "Ljdk/vm/ci/meta/JavaConstant;"
3252 #define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
3253 #define RESOLVED_METHOD "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
3254 #define FIELDINFO "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl$FieldInfo;"
3255 #define HS_RESOLVED_TYPE "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaType;"
3256 #define HS_INSTALLED_CODE "Ljdk/vm/ci/hotspot/HotSpotInstalledCode;"
3257 #define HS_NMETHOD "Ljdk/vm/ci/hotspot/HotSpotNmethod;"
3258 #define HS_COMPILED_CODE "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
3259 #define HS_CONFIG "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
3260 #define HS_STACK_FRAME_REF "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
3261 #define HS_SPECULATION_LOG "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
3262 #define REFLECTION_EXECUTABLE "Ljava/lang/reflect/Executable;"
3263 #define REFLECTION_FIELD "Ljava/lang/reflect/Field;"
3264
3265 // Types wrapping VM pointers. The ...2 macro is for a pair: (wrapper, pointer)
3266 #define HS_METHOD "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
3267 #define HS_METHOD2 "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;J"
3268 #define HS_KLASS "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
3269 #define HS_KLASS2 "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;J"
3270 #define HS_CONSTANT_POOL "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
3271 #define HS_CONSTANT_POOL2 "Ljdk/vm/ci/hotspot/HotSpotConstantPool;J"
3272
3273 JNINativeMethod CompilerToVM::methods[] = {
3274 {CC "getBytecode", CC "(" HS_METHOD2 ")[B", FN_PTR(getBytecode)},
3275 {CC "getExceptionTableStart", CC "(" HS_METHOD2 ")J", FN_PTR(getExceptionTableStart)},
3276 {CC "getExceptionTableLength", CC "(" HS_METHOD2 ")I", FN_PTR(getExceptionTableLength)},
3277 {CC "findUniqueConcreteMethod", CC "(" HS_KLASS2 HS_METHOD2 ")" HS_METHOD, FN_PTR(findUniqueConcreteMethod)},
3278 {CC "getImplementor", CC "(" HS_KLASS2 ")" HS_KLASS, FN_PTR(getImplementor)},
3279 {CC "getStackTraceElement", CC "(" HS_METHOD2 "I)" STACK_TRACE_ELEMENT, FN_PTR(getStackTraceElement)},
3280 {CC "methodIsIgnoredBySecurityStackWalk", CC "(" HS_METHOD2 ")Z", FN_PTR(methodIsIgnoredBySecurityStackWalk)},
3281 {CC "setNotInlinableOrCompilable", CC "(" HS_METHOD2 ")V", FN_PTR(setNotInlinableOrCompilable)},
3282 {CC "isCompilable", CC "(" HS_METHOD2 ")Z", FN_PTR(isCompilable)},
3283 {CC "hasNeverInlineDirective", CC "(" HS_METHOD2 ")Z", FN_PTR(hasNeverInlineDirective)},
3284 {CC "shouldInlineMethod", CC "(" HS_METHOD2 ")Z", FN_PTR(shouldInlineMethod)},
3285 {CC "lookupType", CC "(" STRING HS_KLASS2 "IZ)" HS_RESOLVED_TYPE, FN_PTR(lookupType)},
3286 {CC "lookupJClass", CC "(J)" HS_RESOLVED_TYPE, FN_PTR(lookupJClass)},
3287 {CC "getJObjectValue", CC "(" OBJECTCONSTANT ")J", FN_PTR(getJObjectValue)},
3288 {CC "getArrayType", CC "(C" HS_KLASS2 ")" HS_KLASS, FN_PTR(getArrayType)},
3289 {CC "lookupClass", CC "(" CLASS ")" HS_RESOLVED_TYPE, FN_PTR(lookupClass)},
3290 {CC "lookupNameInPool", CC "(" HS_CONSTANT_POOL2 "II)" STRING, FN_PTR(lookupNameInPool)},
3291 {CC "lookupNameAndTypeRefIndexInPool", CC "(" HS_CONSTANT_POOL2 "II)I", FN_PTR(lookupNameAndTypeRefIndexInPool)},
3292 {CC "lookupSignatureInPool", CC "(" HS_CONSTANT_POOL2 "II)" STRING, FN_PTR(lookupSignatureInPool)},
3293 {CC "lookupKlassRefIndexInPool", CC "(" HS_CONSTANT_POOL2 "II)I", FN_PTR(lookupKlassRefIndexInPool)},
3294 {CC "lookupKlassInPool", CC "(" HS_CONSTANT_POOL2 "I)Ljava/lang/Object;", FN_PTR(lookupKlassInPool)},
3295 {CC "lookupAppendixInPool", CC "(" HS_CONSTANT_POOL2 "II)" OBJECTCONSTANT, FN_PTR(lookupAppendixInPool)},
3296 {CC "lookupMethodInPool", CC "(" HS_CONSTANT_POOL2 "IB" HS_METHOD2 ")" HS_METHOD, FN_PTR(lookupMethodInPool)},
3297 {CC "lookupConstantInPool", CC "(" HS_CONSTANT_POOL2 "IZ)" JAVACONSTANT, FN_PTR(lookupConstantInPool)},
3298 {CC "resolveBootstrapMethod", CC "(" HS_CONSTANT_POOL2 "I)[" OBJECT, FN_PTR(resolveBootstrapMethod)},
3299 {CC "bootstrapArgumentIndexAt", CC "(" HS_CONSTANT_POOL2 "II)I", FN_PTR(bootstrapArgumentIndexAt)},
3300 {CC "getUncachedStringInPool", CC "(" HS_CONSTANT_POOL2 "I)" JAVACONSTANT, FN_PTR(getUncachedStringInPool)},
3301 {CC "resolveTypeInPool", CC "(" HS_CONSTANT_POOL2 "I)" HS_KLASS, FN_PTR(resolveTypeInPool)},
3302 {CC "resolveFieldInPool", CC "(" HS_CONSTANT_POOL2 "I" HS_METHOD2 "B[I)" HS_KLASS, FN_PTR(resolveFieldInPool)},
3303 {CC "decodeFieldIndexToCPIndex", CC "(" HS_CONSTANT_POOL2 "I)I", FN_PTR(decodeFieldIndexToCPIndex)},
3304 {CC "decodeMethodIndexToCPIndex", CC "(" HS_CONSTANT_POOL2 "I)I", FN_PTR(decodeMethodIndexToCPIndex)},
3305 {CC "decodeIndyIndexToCPIndex", CC "(" HS_CONSTANT_POOL2 "IZ)I", FN_PTR(decodeIndyIndexToCPIndex)},
3306 {CC "resolveInvokeHandleInPool", CC "(" HS_CONSTANT_POOL2 "I)V", FN_PTR(resolveInvokeHandleInPool)},
3307 {CC "isResolvedInvokeHandleInPool", CC "(" HS_CONSTANT_POOL2 "II)I", FN_PTR(isResolvedInvokeHandleInPool)},
3308 {CC "resolveMethod", CC "(" HS_KLASS2 HS_METHOD2 HS_KLASS2 ")" HS_METHOD, FN_PTR(resolveMethod)},
3309 {CC "getSignaturePolymorphicHolders", CC "()[" STRING, FN_PTR(getSignaturePolymorphicHolders)},
3310 {CC "getVtableIndexForInterfaceMethod", CC "(" HS_KLASS2 HS_METHOD2 ")I", FN_PTR(getVtableIndexForInterfaceMethod)},
3311 {CC "getClassInitializer", CC "(" HS_KLASS2 ")" HS_METHOD, FN_PTR(getClassInitializer)},
3312 {CC "hasFinalizableSubclass", CC "(" HS_KLASS2 ")Z", FN_PTR(hasFinalizableSubclass)},
3313 {CC "getMaxCallTargetOffset", CC "(J)J", FN_PTR(getMaxCallTargetOffset)},
3314 {CC "asResolvedJavaMethod", CC "(" EXECUTABLE ")" HS_METHOD, FN_PTR(asResolvedJavaMethod)},
3315 {CC "getResolvedJavaMethod", CC "(" OBJECTCONSTANT "J)" HS_METHOD, FN_PTR(getResolvedJavaMethod)},
3316 {CC "getConstantPool", CC "(" OBJECT "JZ)" HS_CONSTANT_POOL, FN_PTR(getConstantPool)},
3317 {CC "getResolvedJavaType0", CC "(Ljava/lang/Object;JZ)" HS_KLASS, FN_PTR(getResolvedJavaType0)},
3318 {CC "readConfiguration", CC "()[" OBJECT, FN_PTR(readConfiguration)},
3319 {CC "installCode0", CC "(JJZ" HS_COMPILED_CODE "[" OBJECT INSTALLED_CODE "J[B)I", FN_PTR(installCode0)},
3320 {CC "getInstallCodeFlags", CC "()I", FN_PTR(getInstallCodeFlags)},
3321 {CC "resetCompilationStatistics", CC "()V", FN_PTR(resetCompilationStatistics)},
3322 {CC "disassembleCodeBlob", CC "(" INSTALLED_CODE ")" STRING, FN_PTR(disassembleCodeBlob)},
3323 {CC "executeHotSpotNmethod", CC "([" OBJECT HS_NMETHOD ")" OBJECT, FN_PTR(executeHotSpotNmethod)},
3324 {CC "getLineNumberTable", CC "(" HS_METHOD2 ")[J", FN_PTR(getLineNumberTable)},
3325 {CC "getLocalVariableTableStart", CC "(" HS_METHOD2 ")J", FN_PTR(getLocalVariableTableStart)},
3326 {CC "getLocalVariableTableLength", CC "(" HS_METHOD2 ")I", FN_PTR(getLocalVariableTableLength)},
3327 {CC "reprofile", CC "(" HS_METHOD2 ")V", FN_PTR(reprofile)},
3328 {CC "invalidateHotSpotNmethod", CC "(" HS_NMETHOD "Z)V", FN_PTR(invalidateHotSpotNmethod)},
3329 {CC "collectCounters", CC "()[J", FN_PTR(collectCounters)},
3330 {CC "getCountersSize", CC "()I", FN_PTR(getCountersSize)},
3331 {CC "setCountersSize", CC "(I)Z", FN_PTR(setCountersSize)},
3332 {CC "allocateCompileId", CC "(" HS_METHOD2 "I)I", FN_PTR(allocateCompileId)},
3333 {CC "isMature", CC "(J)Z", FN_PTR(isMature)},
3334 {CC "hasCompiledCodeForOSR", CC "(" HS_METHOD2 "II)Z", FN_PTR(hasCompiledCodeForOSR)},
3335 {CC "getSymbol", CC "(J)" STRING, FN_PTR(getSymbol)},
3336 {CC "getSignatureName", CC "(J)" STRING, FN_PTR(getSignatureName)},
3337 {CC "iterateFrames", CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT, FN_PTR(iterateFrames)},
3338 {CC "materializeVirtualObjects", CC "(" HS_STACK_FRAME_REF "Z)V", FN_PTR(materializeVirtualObjects)},
3339 {CC "shouldDebugNonSafepoints", CC "()Z", FN_PTR(shouldDebugNonSafepoints)},
3340 {CC "writeDebugOutput", CC "(JIZ)V", FN_PTR(writeDebugOutput)},
3341 {CC "flushDebugOutput", CC "()V", FN_PTR(flushDebugOutput)},
3342 {CC "methodDataProfileDataSize", CC "(JI)I", FN_PTR(methodDataProfileDataSize)},
3343 {CC "methodDataExceptionSeen", CC "(JI)I", FN_PTR(methodDataExceptionSeen)},
3344 {CC "interpreterFrameSize", CC "(" BYTECODE_FRAME ")I", FN_PTR(interpreterFrameSize)},
3345 {CC "compileToBytecode", CC "(" OBJECTCONSTANT ")V", FN_PTR(compileToBytecode)},
3346 {CC "getFlagValue", CC "(" STRING ")" OBJECT, FN_PTR(getFlagValue)},
3347 {CC "getInterfaces", CC "(" HS_KLASS2 ")[" HS_KLASS, FN_PTR(getInterfaces)},
3348 {CC "getComponentType", CC "(" HS_KLASS2 ")" HS_RESOLVED_TYPE, FN_PTR(getComponentType)},
3349 {CC "ensureInitialized", CC "(" HS_KLASS2 ")V", FN_PTR(ensureInitialized)},
3350 {CC "ensureLinked", CC "(" HS_KLASS2 ")V", FN_PTR(ensureLinked)},
3351 {CC "getIdentityHashCode", CC "(" OBJECTCONSTANT ")I", FN_PTR(getIdentityHashCode)},
3352 {CC "isInternedString", CC "(" OBJECTCONSTANT ")Z", FN_PTR(isInternedString)},
3353 {CC "unboxPrimitive", CC "(" OBJECTCONSTANT ")" OBJECT, FN_PTR(unboxPrimitive)},
3354 {CC "boxPrimitive", CC "(" OBJECT ")" OBJECTCONSTANT, FN_PTR(boxPrimitive)},
3355 {CC "getDeclaredConstructors", CC "(" HS_KLASS2 ")[" RESOLVED_METHOD, FN_PTR(getDeclaredConstructors)},
3356 {CC "getDeclaredMethods", CC "(" HS_KLASS2 ")[" RESOLVED_METHOD, FN_PTR(getDeclaredMethods)},
3357 {CC "getDeclaredFieldsInfo", CC "(" HS_KLASS2 ")[" FIELDINFO, FN_PTR(getDeclaredFieldsInfo)},
3358 {CC "readStaticFieldValue", CC "(" HS_KLASS2 "JC)" JAVACONSTANT, FN_PTR(readStaticFieldValue)},
3359 {CC "readFieldValue", CC "(" OBJECTCONSTANT HS_KLASS2 "JC)" JAVACONSTANT, FN_PTR(readFieldValue)},
3360 {CC "isInstance", CC "(" HS_KLASS2 OBJECTCONSTANT ")Z", FN_PTR(isInstance)},
3361 {CC "isAssignableFrom", CC "(" HS_KLASS2 HS_KLASS2 ")Z", FN_PTR(isAssignableFrom)},
3362 {CC "isTrustedForIntrinsics", CC "(" HS_KLASS2 ")Z", FN_PTR(isTrustedForIntrinsics)},
3363 {CC "asJavaType", CC "(" OBJECTCONSTANT ")" HS_RESOLVED_TYPE, FN_PTR(asJavaType)},
3364 {CC "asString", CC "(" OBJECTCONSTANT ")" STRING, FN_PTR(asString)},
3365 {CC "equals", CC "(" OBJECTCONSTANT "J" OBJECTCONSTANT "J)Z", FN_PTR(equals)},
3366 {CC "getJavaMirror", CC "(" HS_KLASS2 ")" OBJECTCONSTANT, FN_PTR(getJavaMirror)},
3367 {CC "getArrayLength", CC "(" OBJECTCONSTANT ")I", FN_PTR(getArrayLength)},
3368 {CC "readArrayElement", CC "(" OBJECTCONSTANT "I)Ljava/lang/Object;", FN_PTR(readArrayElement)},
3369 {CC "arrayBaseOffset", CC "(C)I", FN_PTR(arrayBaseOffset)},
3370 {CC "arrayIndexScale", CC "(C)I", FN_PTR(arrayIndexScale)},
3371 {CC "clearOopHandle", CC "(J)V", FN_PTR(clearOopHandle)},
3372 {CC "releaseClearedOopHandles", CC "()V", FN_PTR(releaseClearedOopHandles)},
3373 {CC "registerNativeMethods", CC "(" CLASS ")[J", FN_PTR(registerNativeMethods)},
3374 {CC "isCurrentThreadAttached", CC "()Z", FN_PTR(isCurrentThreadAttached)},
3375 {CC "getCurrentJavaThread", CC "()J", FN_PTR(getCurrentJavaThread)},
3376 {CC "attachCurrentThread", CC "([BZ[J)Z", FN_PTR(attachCurrentThread)},
3377 {CC "detachCurrentThread", CC "(Z)Z", FN_PTR(detachCurrentThread)},
3378 {CC "translate", CC "(" OBJECT "Z)J", FN_PTR(translate)},
3379 {CC "unhand", CC "(J)" OBJECT, FN_PTR(unhand)},
3380 {CC "updateHotSpotNmethod", CC "(" HS_NMETHOD ")V", FN_PTR(updateHotSpotNmethod)},
3381 {CC "getCode", CC "(" HS_INSTALLED_CODE ")[B", FN_PTR(getCode)},
3382 {CC "asReflectionExecutable", CC "(" HS_METHOD2 ")" REFLECTION_EXECUTABLE, FN_PTR(asReflectionExecutable)},
3383 {CC "asReflectionField", CC "(" HS_KLASS2 "I)" REFLECTION_FIELD, FN_PTR(asReflectionField)},
3384 {CC "getEncodedClassAnnotationData", CC "(" HS_KLASS2 OBJECT "IJ)[B", FN_PTR(getEncodedClassAnnotationData)},
3385 {CC "getEncodedExecutableAnnotationData", CC "(" HS_METHOD2 OBJECT "IJ)[B", FN_PTR(getEncodedExecutableAnnotationData)},
3386 {CC "getEncodedFieldAnnotationData", CC "(" HS_KLASS2 "I" OBJECT "IJ)[B", FN_PTR(getEncodedFieldAnnotationData)},
3387 {CC "getFailedSpeculations", CC "(J[[B)[[B", FN_PTR(getFailedSpeculations)},
3388 {CC "getFailedSpeculationsAddress", CC "(" HS_METHOD2 ")J", FN_PTR(getFailedSpeculationsAddress)},
3389 {CC "releaseFailedSpeculations", CC "(J)V", FN_PTR(releaseFailedSpeculations)},
3390 {CC "addFailedSpeculation", CC "(J[B)Z", FN_PTR(addFailedSpeculation)},
3391 {CC "callSystemExit", CC "(I)V", FN_PTR(callSystemExit)},
3392 {CC "ticksNow", CC "()J", FN_PTR(ticksNow)},
3393 {CC "getThreadLocalObject", CC "(I)" OBJECT, FN_PTR(getThreadLocalObject)},
3394 {CC "setThreadLocalObject", CC "(I" OBJECT ")V", FN_PTR(setThreadLocalObject)},
3395 {CC "getThreadLocalLong", CC "(I)J", FN_PTR(getThreadLocalLong)},
3396 {CC "setThreadLocalLong", CC "(IJ)V", FN_PTR(setThreadLocalLong)},
3397 {CC "registerCompilerPhase", CC "(" STRING ")I", FN_PTR(registerCompilerPhase)},
3398 {CC "notifyCompilerPhaseEvent", CC "(JIII)V", FN_PTR(notifyCompilerPhaseEvent)},
3399 {CC "notifyCompilerInliningEvent", CC "(I" HS_METHOD2 HS_METHOD2 "ZLjava/lang/String;I)V", FN_PTR(notifyCompilerInliningEvent)},
3400 {CC "getOopMapAt", CC "(" HS_METHOD2 "I[J)V", FN_PTR(getOopMapAt)},
3401 {CC "updateCompilerThreadCanCallJava", CC "(Z)Z", FN_PTR(updateCompilerThreadCanCallJava)},
3402 {CC "getCompilationActivityMode", CC "()I", FN_PTR(getCompilationActivityMode)},
3403 {CC "isCompilerThread", CC "()Z", FN_PTR(isCompilerThread)},
3404 };
3405
3406 int CompilerToVM::methods_count() {
3407 return sizeof(methods) / sizeof(JNINativeMethod);
3408 }
--- EOF ---