1 /*
   2  * Copyright (c) 2011, 2024, 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 "precompiled.hpp"
  25 #include "classfile/classLoaderData.inline.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "code/scopeDesc.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compilerEvent.hpp"
  34 #include "compiler/compilerOracle.hpp"
  35 #include "compiler/disassembler.hpp"
  36 #include "compiler/oopMap.hpp"
  37 #include "interpreter/bytecodeStream.hpp"
  38 #include "interpreter/linkResolver.hpp"
  39 #include "interpreter/oopMapCache.hpp"
  40 #include "jfr/jfrEvents.hpp"
  41 #include "jvmci/jvmciCodeInstaller.hpp"
  42 #include "jvmci/jvmciCompilerToVM.hpp"
  43 #include "jvmci/jvmciRuntime.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logTag.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/universe.hpp"
  48 #include "oops/constantPool.inline.hpp"
  49 #include "oops/instanceKlass.inline.hpp"
  50 #include "oops/instanceMirrorKlass.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/objArrayKlass.inline.hpp"
  53 #include "oops/typeArrayOop.inline.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "prims/methodHandles.hpp"
  56 #include "prims/nativeLookup.hpp"
  57 #include "runtime/arguments.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/deoptimization.hpp"
  60 #include "runtime/fieldDescriptor.inline.hpp"
  61 #include "runtime/frame.inline.hpp"
  62 #include "runtime/globals_extension.hpp"
  63 #include "runtime/interfaceSupport.inline.hpp"
  64 #include "runtime/jniHandles.inline.hpp"
  65 #include "runtime/keepStackGCProcessed.hpp"
  66 #include "runtime/reflection.hpp"
  67 #include "runtime/stackFrameStream.inline.hpp"
  68 #include "runtime/timerTrace.hpp"
  69 #include "runtime/vframe.inline.hpp"
  70 #include "runtime/vframe_hp.hpp"
  71 #if INCLUDE_JFR
  72 #include "jfr/jfr.hpp"
  73 #endif
  74 
  75 JVMCIKlassHandle::JVMCIKlassHandle(Thread* thread, Klass* klass) {
  76   _thread = thread;
  77   _klass = klass;
  78   if (klass != nullptr) {
  79     _holder = Handle(_thread, klass->klass_holder());
  80   }
  81 }
  82 
  83 JVMCIKlassHandle& JVMCIKlassHandle::operator=(Klass* klass) {
  84   _klass = klass;
  85   if (klass != nullptr) {
  86     _holder = Handle(_thread, klass->klass_holder());
  87   }
  88   return *this;
  89 }
  90 
  91 static void requireInHotSpot(const char* caller, JVMCI_TRAPS) {
  92   if (!JVMCIENV->is_hotspot()) {
  93     JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from JVMCI shared library", caller));
  94   }
  95 }
  96 
  97 static void requireNotInHotSpot(const char* caller, JVMCI_TRAPS) {
  98     if (JVMCIENV->is_hotspot()) {
  99         JVMCI_THROW_MSG(IllegalStateException, err_msg("Cannot call %s from HotSpot", caller));
 100     }
 101 }
 102 
 103 class JVMCITraceMark : public StackObj {
 104   const char* _msg;
 105  public:
 106   JVMCITraceMark(const char* msg) {
 107     _msg = msg;
 108     JVMCI_event_2("Enter %s", _msg);
 109   }
 110   ~JVMCITraceMark() {
 111     JVMCI_event_2(" Exit %s", _msg);
 112   }
 113 };
 114 
 115 class JavaArgumentUnboxer : public SignatureIterator {
 116  protected:
 117   JavaCallArguments*  _jca;
 118   arrayOop _args;
 119   int _index;
 120 
 121   Handle next_arg(BasicType expectedType);
 122 
 123  public:
 124   JavaArgumentUnboxer(Symbol* signature,
 125                       JavaCallArguments* jca,
 126                       arrayOop args,
 127                       bool is_static)
 128     : SignatureIterator(signature)
 129   {
 130     this->_return_type = T_ILLEGAL;
 131     _jca = jca;
 132     _index = 0;
 133     _args = args;
 134     if (!is_static) {
 135       _jca->push_oop(next_arg(T_OBJECT));
 136     }
 137     do_parameters_on(this);
 138     assert(_index == args->length(), "arg count mismatch with signature");
 139   }
 140 
 141  private:
 142   friend class SignatureIterator;  // so do_parameters_on can call do_type
 143   void do_type(BasicType type) {
 144     if (is_reference_type(type)) {
 145       _jca->push_oop(next_arg(T_OBJECT));
 146       return;
 147     }
 148     Handle arg = next_arg(type);
 149     int box_offset = java_lang_boxing_object::value_offset(type);
 150     switch (type) {
 151     case T_BOOLEAN:     _jca->push_int(arg->bool_field(box_offset));    break;
 152     case T_CHAR:        _jca->push_int(arg->char_field(box_offset));    break;
 153     case T_SHORT:       _jca->push_int(arg->short_field(box_offset));   break;
 154     case T_BYTE:        _jca->push_int(arg->byte_field(box_offset));    break;
 155     case T_INT:         _jca->push_int(arg->int_field(box_offset));     break;
 156     case T_LONG:        _jca->push_long(arg->long_field(box_offset));   break;
 157     case T_FLOAT:       _jca->push_float(arg->float_field(box_offset));    break;
 158     case T_DOUBLE:      _jca->push_double(arg->double_field(box_offset));  break;
 159     default:            ShouldNotReachHere();
 160     }
 161   }
 162 };
 163 
 164 Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
 165   assert(_index < _args->length(), "out of bounds");
 166   oop arg=((objArrayOop) (_args))->obj_at(_index++);
 167   assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
 168   return Handle(Thread::current(), arg);
 169 }
 170 
 171 // Bring the JVMCI compiler thread into the VM state.
 172 #define JVMCI_VM_ENTRY_MARK                                       \
 173   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));       \
 174   ThreadInVMfromNative __tiv(thread);                             \
 175   HandleMarkCleaner __hm(thread);                                 \
 176   JavaThread* THREAD = thread;                                    \
 177   debug_only(VMNativeEntryWrapper __vew;)
 178 
 179 // Native method block that transitions current thread to '_thread_in_vm'.
 180 // Note: CompilerThreadCanCallJava must precede JVMCIENV_FROM_JNI so that
 181 // the translation of an uncaught exception in the JVMCIEnv does not make
 182 // a Java call when __is_hotspot == false.
 183 #define C2V_BLOCK(result_type, name, signature)            \
 184   JVMCI_VM_ENTRY_MARK;                                     \
 185   ResourceMark rm;                                         \
 186   bool __is_hotspot = env == thread->jni_environment();    \
 187   CompilerThreadCanCallJava ccj(thread, __is_hotspot);     \
 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_NULL(jobject, getResolvedJavaMethod, (JNIEnv* env, jobject, jobject base, jlong offset))
 405   Method* method = nullptr;
 406   JVMCIObject base_object = JVMCIENV->wrap(base);
 407   if (base_object.is_null()) {
 408     method = *((Method**)(offset));
 409   } else {
 410     Handle obj = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 411     if (obj->is_a(vmClasses::ResolvedMethodName_klass())) {
 412       method = (Method*) (intptr_t) obj->long_field(offset);
 413     } else {
 414       JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", obj->klass()->external_name()));
 415     }
 416   }
 417   if (method == nullptr) {
 418     JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Unexpected type: %s", JVMCIENV->klass_name(base_object)));
 419   }
 420   assert (method->is_method(), "invalid read");
 421   JVMCIObject result = JVMCIENV->get_jvmci_method(methodHandle(THREAD, method), JVMCI_CHECK_NULL);
 422   return JVMCIENV->get_jobject(result);
 423 }
 424 
 425 C2V_VMENTRY_NULL(jobject, getConstantPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass_or_method), jboolean is_klass))
 426   ConstantPool* cp = nullptr;
 427   if (UNPACK_PAIR(address, klass_or_method) == nullptr) {
 428     JVMCI_THROW_NULL(NullPointerException);
 429   }
 430   if (!is_klass) {
 431     cp = (UNPACK_PAIR(Method, klass_or_method))->constMethod()->constants();
 432   } else {
 433     cp = InstanceKlass::cast(UNPACK_PAIR(Klass, klass_or_method))->constants();
 434   }
 435 
 436   JVMCIObject result = JVMCIENV->get_jvmci_constant_pool(constantPoolHandle(THREAD, cp), JVMCI_CHECK_NULL);
 437   return JVMCIENV->get_jobject(result);
 438 }
 439 
 440 C2V_VMENTRY_NULL(jobject, getResolvedJavaType0, (JNIEnv* env, jobject, jobject base, jlong offset, jboolean compressed))
 441   JVMCIObject base_object = JVMCIENV->wrap(base);
 442   if (base_object.is_null()) {
 443     JVMCI_THROW_MSG_NULL(NullPointerException, "base object is null");
 444   }
 445 
 446   const char* base_desc = nullptr;
 447   JVMCIKlassHandle klass(THREAD);
 448   if (offset == oopDesc::klass_offset_in_bytes()) {
 449     if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
 450       Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 451       klass = base_oop->klass();
 452     } else {
 453       goto unexpected;
 454     }
 455   } else if (!compressed) {
 456     if (JVMCIENV->isa_HotSpotConstantPool(base_object)) {
 457       ConstantPool* cp = JVMCIENV->asConstantPool(base_object);
 458       if (offset == in_bytes(ConstantPool::pool_holder_offset())) {
 459         klass = cp->pool_holder();
 460       } else {
 461         base_desc = FormatBufferResource("[constant pool for %s]", cp->pool_holder()->signature_name());
 462         goto unexpected;
 463       }
 464     } else if (JVMCIENV->isa_HotSpotResolvedObjectTypeImpl(base_object)) {
 465       Klass* base_klass = JVMCIENV->asKlass(base_object);
 466       if (offset == in_bytes(Klass::subklass_offset())) {
 467         klass = base_klass->subklass();
 468       } else if (offset == in_bytes(Klass::super_offset())) {
 469         klass = base_klass->super();
 470       } else if (offset == in_bytes(Klass::next_sibling_offset())) {
 471         klass = base_klass->next_sibling();
 472       } else if (offset == in_bytes(ObjArrayKlass::element_klass_offset()) && base_klass->is_objArray_klass()) {
 473         klass = ObjArrayKlass::cast(base_klass)->element_klass();
 474       } else if (offset >= in_bytes(Klass::primary_supers_offset()) &&
 475                  offset < in_bytes(Klass::primary_supers_offset()) + (int) (sizeof(Klass*) * Klass::primary_super_limit()) &&
 476                  offset % sizeof(Klass*) == 0) {
 477         // Offset is within the primary supers array
 478         int index = (int) ((offset - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*));
 479         klass = base_klass->primary_super_of_depth(index);
 480       } else {
 481         base_desc = FormatBufferResource("[%s]", base_klass->signature_name());
 482         goto unexpected;
 483       }
 484     } else if (JVMCIENV->isa_HotSpotObjectConstantImpl(base_object)) {
 485       Handle base_oop = JVMCIENV->asConstant(base_object, JVMCI_CHECK_NULL);
 486       if (base_oop->is_a(vmClasses::Class_klass())) {
 487         if (offset == java_lang_Class::klass_offset()) {
 488           klass = java_lang_Class::as_Klass(base_oop());
 489         } else if (offset == java_lang_Class::array_klass_offset()) {
 490           klass = java_lang_Class::array_klass_acquire(base_oop());
 491         } else {
 492           base_desc = FormatBufferResource("[Class=%s]", java_lang_Class::as_Klass(base_oop())->signature_name());
 493           goto unexpected;
 494         }
 495       } else {
 496         if (!base_oop.is_null()) {
 497           base_desc = FormatBufferResource("[%s]", base_oop()->klass()->signature_name());
 498         }
 499         goto unexpected;
 500       }
 501     } else if (JVMCIENV->isa_HotSpotMethodData(base_object)) {
 502       jlong base_address = (intptr_t) JVMCIENV->asMethodData(base_object);
 503       klass = *((Klass**) (intptr_t) (base_address + offset));
 504       if (klass == nullptr || !klass->is_loader_alive()) {
 505         // Klasses in methodData might be concurrently unloading so return null in that case.
 506         return nullptr;
 507       }
 508     } else {
 509       goto unexpected;
 510     }
 511   } else {
 512     goto unexpected;
 513   }
 514 
 515   {
 516     if (klass == nullptr) {
 517       return nullptr;
 518     }
 519     JVMCIObject result = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
 520     return JVMCIENV->get_jobject(result);
 521   }
 522 
 523 unexpected:
 524   JVMCI_THROW_MSG_NULL(IllegalArgumentException,
 525                        err_msg("Unexpected arguments: %s%s " JLONG_FORMAT " %s",
 526                                JVMCIENV->klass_name(base_object), base_desc == nullptr ? "" : base_desc,
 527                                offset, compressed ? "true" : "false"));
 528 }
 529 
 530 C2V_VMENTRY_NULL(jobject, findUniqueConcreteMethod, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(method)))
 531   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 532   InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
 533   if (holder->is_interface()) {
 534     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Interface %s should be handled in Java code", holder->external_name()));
 535   }
 536   if (method->can_be_statically_bound()) {
 537     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()));
 538   }
 539 
 540   methodHandle ucm;
 541   {
 542     MutexLocker locker(Compile_lock);
 543     ucm = methodHandle(THREAD, Dependencies::find_unique_concrete_method(holder, method()));
 544   }
 545   JVMCIObject result = JVMCIENV->get_jvmci_method(ucm, JVMCI_CHECK_NULL);
 546   return JVMCIENV->get_jobject(result);
 547 C2V_END
 548 
 549 C2V_VMENTRY_NULL(jobject, getImplementor, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
 550   Klass* klass = UNPACK_PAIR(Klass, klass);
 551   if (!klass->is_interface()) {
 552     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 553                    err_msg("Expected interface type, got %s", klass->external_name()));
 554   }
 555   InstanceKlass* iklass = InstanceKlass::cast(klass);
 556   JVMCIKlassHandle handle(THREAD, iklass->implementor());
 557   JVMCIObject implementor = JVMCIENV->get_jvmci_type(handle, JVMCI_CHECK_NULL);
 558   return JVMCIENV->get_jobject(implementor);
 559 C2V_END
 560 
 561 C2V_VMENTRY_0(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 562   Method* method = UNPACK_PAIR(Method, method);
 563   return method->is_ignored_by_security_stack_walk();
 564 C2V_END
 565 
 566 C2V_VMENTRY_0(jboolean, isCompilable,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 567   Method* method = UNPACK_PAIR(Method, method);
 568   // Skip redefined methods
 569   if (method->is_old()) {
 570     return false;
 571   }
 572   return !method->is_not_compilable(CompLevel_full_optimization);
 573 C2V_END
 574 
 575 C2V_VMENTRY_0(jboolean, hasNeverInlineDirective,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 576   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 577   return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
 578 C2V_END
 579 
 580 C2V_VMENTRY_0(jboolean, shouldInlineMethod,(JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
 581   methodHandle method (THREAD, UNPACK_PAIR(Method, method));
 582   return CompilerOracle::should_inline(method) || method->force_inline();
 583 C2V_END
 584 
 585 C2V_VMENTRY_NULL(jobject, lookupType, (JNIEnv* env, jobject, jstring jname, ARGUMENT_PAIR(accessing_klass), jint accessing_klass_loader, jboolean resolve))
 586   CompilerThreadCanCallJava canCallJava(thread, resolve); // Resolution requires Java calls
 587   JVMCIObject name = JVMCIENV->wrap(jname);
 588   const char* str = JVMCIENV->as_utf8_string(name);
 589   TempNewSymbol class_name = SymbolTable::new_symbol(str);
 590 
 591   if (class_name->utf8_length() <= 1) {
 592     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Primitive type %s should be handled in Java code", str));
 593   }
 594 
 595 #ifdef ASSERT
 596   const char* val = Arguments::PropertyList_get_value(Arguments::system_properties(), "test.jvmci.lookupTypeException");
 597   if (val != nullptr) {
 598     if (strstr(val, "<trace>") != nullptr) {
 599       tty->print_cr("CompilerToVM.lookupType: %s", str);
 600     } else if (strstr(str, val) != nullptr) {
 601       THROW_MSG_NULL(vmSymbols::java_lang_Exception(),
 602                      err_msg("lookupTypeException: %s", str));
 603     }
 604   }
 605 #endif
 606 
 607   JVMCIKlassHandle resolved_klass(THREAD);
 608   Klass* accessing_klass = UNPACK_PAIR(Klass, accessing_klass);
 609   Handle class_loader;
 610   Handle protection_domain;
 611   if (accessing_klass != nullptr) {
 612     class_loader = Handle(THREAD, accessing_klass->class_loader());
 613     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
 614   } else {
 615     switch (accessing_klass_loader) {
 616       case 0: break; // class_loader is already null, the boot loader
 617       case 1: class_loader = Handle(THREAD, SystemDictionary::java_platform_loader()); break;
 618       case 2: class_loader = Handle(THREAD, SystemDictionary::java_system_loader()); break;
 619       default:
 620         JVMCI_THROW_MSG_NULL(InternalError, err_msg("Illegal class loader value: %d", accessing_klass_loader));
 621     }
 622     JVMCIENV->runtime()->initialize(JVMCI_CHECK_NULL);
 623   }
 624 
 625   if (resolve) {
 626     resolved_klass = SystemDictionary::resolve_or_fail(class_name, class_loader, protection_domain, true, CHECK_NULL);
 627   } else {
 628     if (Signature::has_envelope(class_name)) {
 629       // This is a name from a signature.  Strip off the trimmings.
 630       // Call recursive to keep scope of strippedsym.
 631       TempNewSymbol strippedsym = Signature::strip_envelope(class_name);
 632       resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
 633                                                              class_loader,
 634                                                              protection_domain);
 635     } else if (Signature::is_array(class_name)) {
 636       SignatureStream ss(class_name, false);
 637       int ndim = ss.skip_array_prefix();
 638       if (ss.type() == T_OBJECT) {
 639         Symbol* strippedsym = ss.as_symbol();
 640         resolved_klass = SystemDictionary::find_instance_klass(THREAD, strippedsym,
 641                                                                class_loader,
 642                                                                protection_domain);
 643         if (!resolved_klass.is_null()) {
 644           resolved_klass = resolved_klass->array_klass(ndim, CHECK_NULL);
 645         }
 646       } else {
 647         resolved_klass = Universe::typeArrayKlass(ss.type())->array_klass(ndim, CHECK_NULL);
 648       }
 649     } else {
 650       resolved_klass = SystemDictionary::find_instance_klass(THREAD, class_name,
 651                                                              class_loader,
 652                                                              protection_domain);
 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_int());
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();
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     method_data->initialize();
1380   }
1381 C2V_END
1382 
1383 
1384 C2V_VMENTRY(void, invalidateHotSpotNmethod, (JNIEnv* env, jobject, jobject hs_nmethod, jboolean deoptimize))
1385   JVMCIObject nmethod_mirror = JVMCIENV->wrap(hs_nmethod);
1386   JVMCIENV->invalidate_nmethod_mirror(nmethod_mirror, deoptimize, JVMCI_CHECK);
1387 C2V_END
1388 
1389 C2V_VMENTRY_NULL(jlongArray, collectCounters, (JNIEnv* env, jobject))
1390   // Returns a zero length array if counters aren't enabled
1391   JVMCIPrimitiveArray array = JVMCIENV->new_longArray(JVMCICounterSize, JVMCI_CHECK_NULL);
1392   if (JVMCICounterSize > 0) {
1393     jlong* temp_array = NEW_RESOURCE_ARRAY(jlong, JVMCICounterSize);
1394     JavaThread::collect_counters(temp_array, JVMCICounterSize);
1395     JVMCIENV->copy_longs_from(temp_array, array, 0, JVMCICounterSize);
1396   }
1397   return (jlongArray) JVMCIENV->get_jobject(array);
1398 C2V_END
1399 
1400 C2V_VMENTRY_0(jint, getCountersSize, (JNIEnv* env, jobject))
1401   return (jint) JVMCICounterSize;
1402 C2V_END
1403 
1404 C2V_VMENTRY_0(jboolean, setCountersSize, (JNIEnv* env, jobject, jint new_size))
1405   return JavaThread::resize_all_jvmci_counters(new_size);
1406 C2V_END
1407 
1408 C2V_VMENTRY_0(jint, allocateCompileId, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci))
1409   HandleMark hm(THREAD);
1410   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
1411   if (method.is_null()) {
1412     JVMCI_THROW_0(NullPointerException);
1413   }
1414   if (entry_bci >= method->code_size() || entry_bci < -1) {
1415     JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Unexpected bci %d", entry_bci));
1416   }
1417   return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
1418 C2V_END
1419 
1420 
1421 C2V_VMENTRY_0(jboolean, isMature, (JNIEnv* env, jobject, jlong method_data_pointer))
1422   MethodData* mdo = (MethodData*) method_data_pointer;
1423   return mdo != nullptr && mdo->is_mature();
1424 C2V_END
1425 
1426 C2V_VMENTRY_0(jboolean, hasCompiledCodeForOSR, (JNIEnv* env, jobject, ARGUMENT_PAIR(method), int entry_bci, int comp_level))
1427   Method* method = UNPACK_PAIR(Method, method);
1428   return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != nullptr;
1429 C2V_END
1430 
1431 C2V_VMENTRY_NULL(jobject, getSymbol, (JNIEnv* env, jobject, jlong symbol))
1432   JVMCIObject sym = JVMCIENV->create_string((Symbol*)(address)symbol, JVMCI_CHECK_NULL);
1433   return JVMCIENV->get_jobject(sym);
1434 C2V_END
1435 
1436 C2V_VMENTRY_NULL(jobject, getSignatureName, (JNIEnv* env, jobject, jlong klass_pointer))
1437   Klass* klass = UNPACK_PAIR(Klass, klass);
1438   JVMCIObject signature = JVMCIENV->create_string(klass->signature_name(), JVMCI_CHECK_NULL);
1439   return JVMCIENV->get_jobject(signature);
1440 C2V_END
1441 
1442 /*
1443  * Used by matches() to convert a ResolvedJavaMethod[] to an array of Method*.
1444  */
1445 static GrowableArray<Method*>* init_resolved_methods(jobjectArray methods, JVMCIEnv* JVMCIENV) {
1446   objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
1447   GrowableArray<Method*>* resolved_methods = new GrowableArray<Method*>(methods_oop->length());
1448   for (int i = 0; i < methods_oop->length(); i++) {
1449     oop resolved = methods_oop->obj_at(i);
1450     Method* resolved_method = nullptr;
1451     if (resolved->klass() == HotSpotJVMCI::HotSpotResolvedJavaMethodImpl::klass()) {
1452       resolved_method = HotSpotJVMCI::asMethod(JVMCIENV, resolved);
1453     }
1454     resolved_methods->append(resolved_method);
1455   }
1456   return resolved_methods;
1457 }
1458 
1459 /*
1460  * Used by c2v_iterateFrames to check if `method` matches one of the ResolvedJavaMethods in the `methods` array.
1461  * The ResolvedJavaMethod[] array is converted to a Method* array that is then cached in the resolved_methods_ref in/out parameter.
1462  * In case of a match, the matching ResolvedJavaMethod is returned in matched_jvmci_method_ref.
1463  */
1464 static bool matches(jobjectArray methods, Method* method, GrowableArray<Method*>** resolved_methods_ref, Handle* matched_jvmci_method_ref, Thread* THREAD, JVMCIEnv* JVMCIENV) {
1465   GrowableArray<Method*>* resolved_methods = *resolved_methods_ref;
1466   if (resolved_methods == nullptr) {
1467     resolved_methods = init_resolved_methods(methods, JVMCIENV);
1468     *resolved_methods_ref = resolved_methods;
1469   }
1470   assert(method != nullptr, "method should not be null");
1471   assert(resolved_methods->length() == ((objArrayOop) JNIHandles::resolve(methods))->length(), "arrays must have the same length");
1472   for (int i = 0; i < resolved_methods->length(); i++) {
1473     Method* m = resolved_methods->at(i);
1474     if (m == method) {
1475       *matched_jvmci_method_ref = Handle(THREAD, ((objArrayOop) JNIHandles::resolve(methods))->obj_at(i));
1476       return true;
1477     }
1478   }
1479   return false;
1480 }
1481 
1482 /*
1483  * Resolves an interface call to a concrete method handle.
1484  */
1485 static methodHandle resolve_interface_call(Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
1486   CallInfo callinfo;
1487   Handle receiver = args->receiver();
1488   Klass* recvrKlass = receiver.is_null() ? (Klass*)nullptr : receiver->klass();
1489   LinkInfo link_info(spec_klass, name, signature);
1490   LinkResolver::resolve_interface_call(
1491           callinfo, receiver, recvrKlass, link_info, true, CHECK_(methodHandle()));
1492   methodHandle method(THREAD, callinfo.selected_method());
1493   assert(method.not_null(), "should have thrown exception");
1494   return method;
1495 }
1496 
1497 /*
1498  * Used by c2v_iterateFrames to make a new vframeStream at the given compiled frame id (stack pointer) and vframe id.
1499  */
1500 static void resync_vframestream_to_compiled_frame(vframeStream& vfst, intptr_t* stack_pointer, int vframe_id, JavaThread* thread, TRAPS) {
1501   vfst = vframeStream(thread);
1502   while (vfst.frame_id() != stack_pointer && !vfst.at_end()) {
1503     vfst.next();
1504   }
1505   if (vfst.frame_id() != stack_pointer) {
1506     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1507   }
1508   if (vfst.is_interpreted_frame()) {
1509     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1510   }
1511   while (vfst.vframe_id() != vframe_id) {
1512     if (vfst.at_end()) {
1513       THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
1514     }
1515     vfst.next();
1516     assert(!vfst.is_interpreted_frame(), "Wrong frame type");
1517   }
1518 }
1519 
1520 /*
1521  * Used by c2v_iterateFrames. Returns an array of any unallocated scope objects or null if none.
1522  */
1523 static GrowableArray<ScopeValue*>* get_unallocated_objects_or_null(GrowableArray<ScopeValue*>* scope_objects) {
1524   GrowableArray<ScopeValue*>* unallocated = nullptr;
1525   for (int i = 0; i < scope_objects->length(); i++) {
1526     ObjectValue* sv = (ObjectValue*) scope_objects->at(i);
1527     if (sv->value().is_null()) {
1528       if (unallocated == nullptr) {
1529         unallocated = new GrowableArray<ScopeValue*>(scope_objects->length());
1530       }
1531       unallocated->append(sv);
1532     }
1533   }
1534   return unallocated;
1535 }
1536 
1537 C2V_VMENTRY_NULL(jobject, iterateFrames, (JNIEnv* env, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
1538 
1539   if (!thread->has_last_Java_frame()) {
1540     return nullptr;
1541   }
1542   Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
1543   KeepStackGCProcessedMark keep_stack(THREAD);
1544 
1545   requireInHotSpot("iterateFrames", JVMCI_CHECK_NULL);
1546 
1547   HotSpotJVMCI::HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1548 
1549   vframeStream vfst(thread);
1550   jobjectArray methods = initial_methods;
1551   methodHandle visitor_method;
1552   GrowableArray<Method*>* resolved_methods = nullptr;
1553 
1554   while (!vfst.at_end()) { // frame loop
1555     bool realloc_called = false;
1556     intptr_t* frame_id = vfst.frame_id();
1557 
1558     // Previous compiledVFrame of this frame; use with at_scope() to reuse scope object pool.
1559     compiledVFrame* prev_cvf = nullptr;
1560 
1561     for (; !vfst.at_end() && vfst.frame_id() == frame_id; vfst.next()) { // vframe loop
1562       int frame_number = 0;
1563       Method *method = vfst.method();
1564       int bci = vfst.bci();
1565 
1566       Handle matched_jvmci_method;
1567       if (methods == nullptr || matches(methods, method, &resolved_methods, &matched_jvmci_method, THREAD, JVMCIENV)) {
1568         if (initialSkip > 0) {
1569           initialSkip--;
1570           continue;
1571         }
1572         javaVFrame* vf;
1573         if (prev_cvf != nullptr && prev_cvf->frame_pointer()->id() == frame_id) {
1574           assert(prev_cvf->is_compiled_frame(), "expected compiled Java frame");
1575           vf = prev_cvf->at_scope(vfst.decode_offset(), vfst.vframe_id());
1576         } else {
1577           vf = vfst.asJavaVFrame();
1578         }
1579 
1580         StackValueCollection* locals = nullptr;
1581         typeArrayHandle localIsVirtual_h;
1582         if (vf->is_compiled_frame()) {
1583           // compiled method frame
1584           compiledVFrame* cvf = compiledVFrame::cast(vf);
1585 
1586           ScopeDesc* scope = cvf->scope();
1587           // native wrappers do not have a scope
1588           if (scope != nullptr && scope->objects() != nullptr) {
1589             prev_cvf = cvf;
1590 
1591             GrowableArray<ScopeValue*>* objects = nullptr;
1592             if (!realloc_called) {
1593               objects = scope->objects();
1594             } else {
1595               // some object might already have been re-allocated, only reallocate the non-allocated ones
1596               objects = get_unallocated_objects_or_null(scope->objects());
1597             }
1598 
1599             if (objects != nullptr) {
1600               RegisterMap reg_map(vf->register_map());
1601               bool realloc_failures = Deoptimization::realloc_objects(thread, vf->frame_pointer(), &reg_map, objects, CHECK_NULL);
1602               Deoptimization::reassign_fields(vf->frame_pointer(), &reg_map, objects, realloc_failures, false);
1603               realloc_called = true;
1604             }
1605 
1606             GrowableArray<ScopeValue*>* local_values = scope->locals();
1607             for (int i = 0; i < local_values->length(); i++) {
1608               ScopeValue* value = local_values->at(i);
1609               assert(!value->is_object_merge(), "Should not be.");
1610               if (value->is_object()) {
1611                 if (localIsVirtual_h.is_null()) {
1612                   typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
1613                   localIsVirtual_h = typeArrayHandle(THREAD, array_oop);
1614                 }
1615                 localIsVirtual_h->bool_at_put(i, true);
1616               }
1617             }
1618           }
1619 
1620           locals = cvf->locals();
1621           frame_number = cvf->vframe_id();
1622         } else {
1623           // interpreted method frame
1624           interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1625 
1626           locals = ivf->locals();
1627         }
1628         assert(bci == vf->bci(), "wrong bci");
1629         assert(method == vf->method(), "wrong method");
1630 
1631         Handle frame_reference = HotSpotJVMCI::HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1632         HotSpotJVMCI::HotSpotStackFrameReference::set_bci(JVMCIENV, frame_reference(), bci);
1633         if (matched_jvmci_method.is_null()) {
1634           methodHandle mh(THREAD, method);
1635           JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
1636           matched_jvmci_method = Handle(THREAD, JNIHandles::resolve(jvmci_method.as_jobject()));
1637         }
1638         HotSpotJVMCI::HotSpotStackFrameReference::set_method(JVMCIENV, frame_reference(), matched_jvmci_method());
1639         HotSpotJVMCI::HotSpotStackFrameReference::set_localIsVirtual(JVMCIENV, frame_reference(), localIsVirtual_h());
1640 
1641         HotSpotJVMCI::HotSpotStackFrameReference::set_compilerToVM(JVMCIENV, frame_reference(), JNIHandles::resolve(compilerToVM));
1642         HotSpotJVMCI::HotSpotStackFrameReference::set_stackPointer(JVMCIENV, frame_reference(), (jlong) frame_id);
1643         HotSpotJVMCI::HotSpotStackFrameReference::set_frameNumber(JVMCIENV, frame_reference(), frame_number);
1644 
1645         // initialize the locals array
1646         objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
1647         objArrayHandle array(THREAD, array_oop);
1648         for (int i = 0; i < locals->size(); i++) {
1649           StackValue* var = locals->at(i);
1650           if (var->type() == T_OBJECT) {
1651             array->obj_at_put(i, locals->at(i)->get_obj()());
1652           }
1653         }
1654         HotSpotJVMCI::HotSpotStackFrameReference::set_locals(JVMCIENV, frame_reference(), array());
1655         HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, frame_reference(), JNI_FALSE);
1656 
1657         JavaValue result(T_OBJECT);
1658         JavaCallArguments args(visitor);
1659         if (visitor_method.is_null()) {
1660           visitor_method = resolve_interface_call(HotSpotJVMCI::InspectedFrameVisitor::klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
1661         }
1662 
1663         args.push_oop(frame_reference);
1664         JavaCalls::call(&result, visitor_method, &args, CHECK_NULL);
1665         if (result.get_oop() != nullptr) {
1666           return JNIHandles::make_local(thread, result.get_oop());
1667         }
1668         if (methods == initial_methods) {
1669           methods = match_methods;
1670           if (resolved_methods != nullptr && JNIHandles::resolve(match_methods) != JNIHandles::resolve(initial_methods)) {
1671             resolved_methods = nullptr;
1672           }
1673         }
1674         assert(initialSkip == 0, "There should be no match before initialSkip == 0");
1675         if (HotSpotJVMCI::HotSpotStackFrameReference::objectsMaterialized(JVMCIENV, frame_reference()) == JNI_TRUE) {
1676           // the frame has been deoptimized, we need to re-synchronize the frame and vframe
1677           prev_cvf = nullptr;
1678           intptr_t* stack_pointer = (intptr_t*) HotSpotJVMCI::HotSpotStackFrameReference::stackPointer(JVMCIENV, frame_reference());
1679           resync_vframestream_to_compiled_frame(vfst, stack_pointer, frame_number, thread, CHECK_NULL);
1680         }
1681       }
1682     } // end of vframe loop
1683   } // end of frame loop
1684 
1685   // the end was reached without finding a matching method
1686   return nullptr;
1687 C2V_END
1688 
1689 C2V_VMENTRY_0(int, decodeIndyIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint indy_index, jboolean resolve))
1690   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1691   CallInfo callInfo;
1692   if (resolve) {
1693     LinkResolver::resolve_invoke(callInfo, Handle(), cp, indy_index, Bytecodes::_invokedynamic, CHECK_0);
1694     cp->cache()->set_dynamic_call(callInfo, indy_index);
1695   }
1696   return cp->resolved_indy_entry_at(indy_index)->constant_pool_index();
1697 C2V_END
1698 
1699 C2V_VMENTRY_0(int, decodeFieldIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint field_index))
1700   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1701   if (field_index < 0 || field_index >= cp->resolved_field_entries_length()) {
1702     JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid field index %d", field_index));
1703   }
1704   return cp->resolved_field_entry_at(field_index)->constant_pool_index();
1705 C2V_END
1706 
1707 C2V_VMENTRY_0(int, decodeMethodIndexToCPIndex, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint method_index))
1708   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1709   if (method_index < 0 || method_index >= cp->resolved_method_entries_length()) {
1710     JVMCI_THROW_MSG_0(IllegalStateException, err_msg("invalid method index %d", method_index));
1711   }
1712   return cp->resolved_method_entry_at(method_index)->constant_pool_index();
1713 C2V_END
1714 
1715 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index))
1716   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1717   Klass* holder = cp->klass_ref_at(index, Bytecodes::_invokehandle, CHECK);
1718   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1719   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1720     CallInfo callInfo;
1721     LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1722     cp->cache()->set_method_handle(index, callInfo);
1723   }
1724 C2V_END
1725 
1726 C2V_VMENTRY_0(jint, isResolvedInvokeHandleInPool, (JNIEnv* env, jobject, ARGUMENT_PAIR(cp), jint index, jint opcode))
1727   constantPoolHandle cp(THREAD, UNPACK_PAIR(ConstantPool, cp));
1728   ResolvedMethodEntry* entry = cp->cache()->resolved_method_entry_at(index);
1729   if (entry->is_resolved(Bytecodes::_invokehandle)) {
1730     // MethodHandle.invoke* --> LambdaForm?
1731     ResourceMark rm;
1732 
1733     LinkInfo link_info(cp, index, Bytecodes::_invokehandle, CATCH);
1734 
1735     Klass* resolved_klass = link_info.resolved_klass();
1736 
1737     Symbol* name_sym = cp->name_ref_at(index, Bytecodes::_invokehandle);
1738 
1739     vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
1740     vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
1741 
1742     methodHandle adapter_method(THREAD, entry->method());
1743 
1744     methodHandle resolved_method(adapter_method);
1745 
1746     // Can we treat it as a regular invokevirtual?
1747     if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
1748       vmassert(!resolved_method->is_static(),"!");
1749       vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
1750       vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
1751       vmassert(cp->cache()->appendix_if_resolved(entry) == nullptr, "!");
1752 
1753       methodHandle m(THREAD, LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
1754       vmassert(m == resolved_method, "!!");
1755       return -1;
1756     }
1757 
1758     return Bytecodes::_invokevirtual;
1759   }
1760   if ((Bytecodes::Code)opcode == Bytecodes::_invokedynamic) {
1761     if (cp->resolved_indy_entry_at(index)->is_resolved()) {
1762       return Bytecodes::_invokedynamic;
1763     }
1764   }
1765   return -1;
1766 C2V_END
1767 
1768 
1769 C2V_VMENTRY_NULL(jobject, getSignaturePolymorphicHolders, (JNIEnv* env, jobject))
1770   JVMCIObjectArray holders = JVMCIENV->new_String_array(2, JVMCI_CHECK_NULL);
1771   JVMCIObject mh = JVMCIENV->create_string("Ljava/lang/invoke/MethodHandle;", JVMCI_CHECK_NULL);
1772   JVMCIObject vh = JVMCIENV->create_string("Ljava/lang/invoke/VarHandle;", JVMCI_CHECK_NULL);
1773   JVMCIENV->put_object_at(holders, 0, mh);
1774   JVMCIENV->put_object_at(holders, 1, vh);
1775   return JVMCIENV->get_jobject(holders);
1776 C2V_END
1777 
1778 C2V_VMENTRY_0(jboolean, shouldDebugNonSafepoints, (JNIEnv* env, jobject))
1779   //see compute_recording_non_safepoints in debugInfroRec.cpp
1780   if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1781     return true;
1782   }
1783   return DebugNonSafepoints;
1784 C2V_END
1785 
1786 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1787 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv* env, jobject, jobject _hs_frame, bool invalidate))
1788   JVMCIObject hs_frame = JVMCIENV->wrap(_hs_frame);
1789   if (hs_frame.is_null()) {
1790     JVMCI_THROW_MSG(NullPointerException, "stack frame is null");
1791   }
1792 
1793   requireInHotSpot("materializeVirtualObjects", JVMCI_CHECK);
1794 
1795   JVMCIENV->HotSpotStackFrameReference_initialize(JVMCI_CHECK);
1796 
1797   // look for the given stack frame
1798   StackFrameStream fst(thread, false /* update */, true /* process_frames */);
1799   intptr_t* stack_pointer = (intptr_t*) JVMCIENV->get_HotSpotStackFrameReference_stackPointer(hs_frame);
1800   while (fst.current()->id() != stack_pointer && !fst.is_done()) {
1801     fst.next();
1802   }
1803   if (fst.current()->id() != stack_pointer) {
1804     JVMCI_THROW_MSG(IllegalStateException, "stack frame not found");
1805   }
1806 
1807   if (invalidate) {
1808     if (!fst.current()->is_compiled_frame()) {
1809       JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1810     }
1811     fst.current()->cb()->as_nmethod()->make_not_entrant();
1812   }
1813   Deoptimization::deoptimize(thread, *fst.current(), Deoptimization::Reason_none);
1814   // look for the frame again as it has been updated by deopt (pc, deopt state...)
1815   StackFrameStream fstAfterDeopt(thread, true /* update */, true /* process_frames */);
1816   while (fstAfterDeopt.current()->id() != stack_pointer && !fstAfterDeopt.is_done()) {
1817     fstAfterDeopt.next();
1818   }
1819   if (fstAfterDeopt.current()->id() != stack_pointer) {
1820     JVMCI_THROW_MSG(IllegalStateException, "stack frame not found after deopt");
1821   }
1822 
1823   vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1824   if (!vf->is_compiled_frame()) {
1825     JVMCI_THROW_MSG(IllegalStateException, "compiled stack frame expected");
1826   }
1827 
1828   GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1829   while (true) {
1830     assert(vf->is_compiled_frame(), "Wrong frame type");
1831     virtualFrames->push(compiledVFrame::cast(vf));
1832     if (vf->is_top()) {
1833       break;
1834     }
1835     vf = vf->sender();
1836   }
1837 
1838   int last_frame_number = JVMCIENV->get_HotSpotStackFrameReference_frameNumber(hs_frame);
1839   if (last_frame_number >= virtualFrames->length()) {
1840     JVMCI_THROW_MSG(IllegalStateException, "invalid frame number");
1841   }
1842 
1843   // Reallocate the non-escaping objects and restore their fields.
1844   assert (virtualFrames->at(last_frame_number)->scope() != nullptr,"invalid scope");
1845   GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1846 
1847   if (objects == nullptr) {
1848     // no objects to materialize
1849     return;
1850   }
1851 
1852   bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, CHECK);
1853   Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
1854 
1855   for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1856     compiledVFrame* cvf = virtualFrames->at(frame_index);
1857 
1858     GrowableArray<ScopeValue*>* scopedValues = cvf->scope()->locals();
1859     StackValueCollection* locals = cvf->locals();
1860     if (locals != nullptr) {
1861       for (int i2 = 0; i2 < locals->size(); i2++) {
1862         StackValue* var = locals->at(i2);
1863         assert(!scopedValues->at(i2)->is_object_merge(), "Should not be.");
1864         if (var->type() == T_OBJECT && scopedValues->at(i2)->is_object()) {
1865           jvalue val;
1866           val.l = cast_from_oop<jobject>(locals->at(i2)->get_obj()());
1867           cvf->update_local(T_OBJECT, i2, val);
1868         }
1869       }
1870     }
1871 
1872     GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
1873     StackValueCollection* expressions = cvf->expressions();
1874     if (expressions != nullptr) {
1875       for (int i2 = 0; i2 < expressions->size(); i2++) {
1876         StackValue* var = expressions->at(i2);
1877         assert(!scopeExpressions->at(i2)->is_object_merge(), "Should not be.");
1878         if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
1879           jvalue val;
1880           val.l = cast_from_oop<jobject>(expressions->at(i2)->get_obj()());
1881           cvf->update_stack(T_OBJECT, i2, val);
1882         }
1883       }
1884     }
1885 
1886     GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
1887     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1888     if (monitors != nullptr) {
1889       for (int i2 = 0; i2 < monitors->length(); i2++) {
1890         cvf->update_monitor(i2, monitors->at(i2));
1891       }
1892     }
1893   }
1894 
1895   // all locals are materialized by now
1896   JVMCIENV->set_HotSpotStackFrameReference_localIsVirtual(hs_frame, nullptr);
1897   // update the locals array
1898   JVMCIObjectArray array = JVMCIENV->get_HotSpotStackFrameReference_locals(hs_frame);
1899   StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1900   for (int i = 0; i < locals->size(); i++) {
1901     StackValue* var = locals->at(i);
1902     if (var->type() == T_OBJECT) {
1903       JVMCIENV->put_object_at(array, i, HotSpotJVMCI::wrap(locals->at(i)->get_obj()()));
1904     }
1905   }
1906   HotSpotJVMCI::HotSpotStackFrameReference::set_objectsMaterialized(JVMCIENV, hs_frame, JNI_TRUE);
1907 C2V_END
1908 
1909 // Use of tty does not require the current thread to be attached to the VM
1910 // so no need for a full C2V_VMENTRY transition.
1911 C2V_VMENTRY_PREFIX(void, writeDebugOutput, (JNIEnv* env, jobject, jlong buffer, jint length, bool flush))
1912   if (length <= 8) {
1913     tty->write((char*) &buffer, length);
1914   } else {
1915     tty->write((char*) buffer, length);
1916   }
1917   if (flush) {
1918     tty->flush();
1919   }
1920 C2V_END
1921 
1922 // Use of tty does not require the current thread to be attached to the VM
1923 // so no need for a full C2V_VMENTRY transition.
1924 C2V_VMENTRY_PREFIX(void, flushDebugOutput, (JNIEnv* env, jobject))
1925   tty->flush();
1926 C2V_END
1927 
1928 C2V_VMENTRY_0(jint, methodDataProfileDataSize, (JNIEnv* env, jobject, jlong method_data_pointer, jint position))
1929   MethodData* mdo = (MethodData*) method_data_pointer;
1930   ProfileData* profile_data = mdo->data_at(position);
1931   if (mdo->is_valid(profile_data)) {
1932     return profile_data->size_in_bytes();
1933   }
1934   // Java code should never directly access the extra data section
1935   JVMCI_THROW_MSG_0(IllegalArgumentException, err_msg("Invalid profile data position %d", position));
1936 C2V_END
1937 
1938 C2V_VMENTRY_0(jint, methodDataExceptionSeen, (JNIEnv* env, jobject, jlong method_data_pointer, jint bci))
1939   MethodData* mdo = (MethodData*) method_data_pointer;
1940 
1941   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1942   MutexLocker mu(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
1943 
1944   DataLayout* data    = mdo->extra_data_base();
1945   DataLayout* end   = mdo->args_data_limit();
1946   for (;; data = mdo->next_extra(data)) {
1947     assert(data < end, "moved past end of extra data");
1948     int tag = data->tag();
1949     switch(tag) {
1950       case DataLayout::bit_data_tag: {
1951         BitData* bit_data = (BitData*) data->data_in();
1952         if (bit_data->bci() == bci) {
1953           return bit_data->exception_seen() ? 1 : 0;
1954         }
1955         break;
1956       }
1957     case DataLayout::no_tag:
1958       // There is a free slot so return false since a BitData would have been allocated to record
1959       // true if it had been seen.
1960       return 0;
1961     case DataLayout::arg_info_data_tag:
1962       // The bci wasn't found and there are no free slots to record a trap for this location, so always
1963       // return unknown.
1964       return -1;
1965     }
1966   }
1967   ShouldNotReachHere();
1968   return -1;
1969 C2V_END
1970 
1971 C2V_VMENTRY_NULL(jobject, getInterfaces, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1972   Klass* klass = UNPACK_PAIR(Klass, klass);
1973   if (klass == nullptr) {
1974     JVMCI_THROW_NULL(NullPointerException);
1975   }
1976 
1977   if (!klass->is_instance_klass()) {
1978     JVMCI_THROW_MSG_NULL(InternalError, err_msg("Class %s must be instance klass", klass->external_name()));
1979   }
1980   InstanceKlass* iklass = InstanceKlass::cast(klass);
1981 
1982   // Regular instance klass, fill in all local interfaces
1983   int size = iklass->local_interfaces()->length();
1984   JVMCIObjectArray interfaces = JVMCIENV->new_HotSpotResolvedObjectTypeImpl_array(size, JVMCI_CHECK_NULL);
1985   for (int index = 0; index < size; index++) {
1986     JVMCIKlassHandle klass(THREAD);
1987     Klass* k = iklass->local_interfaces()->at(index);
1988     klass = k;
1989     JVMCIObject type = JVMCIENV->get_jvmci_type(klass, JVMCI_CHECK_NULL);
1990     JVMCIENV->put_object_at(interfaces, index, type);
1991   }
1992   return JVMCIENV->get_jobject(interfaces);
1993 C2V_END
1994 
1995 C2V_VMENTRY_NULL(jobject, getComponentType, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
1996   Klass* klass = UNPACK_PAIR(Klass, klass);
1997   if (klass == nullptr) {
1998     JVMCI_THROW_NULL(NullPointerException);
1999   }
2000 
2001   if (!klass->is_array_klass()) {
2002     return nullptr;
2003   }
2004   oop mirror = klass->java_mirror();
2005   oop component_mirror = java_lang_Class::component_mirror(mirror);
2006   if (component_mirror == nullptr) {
2007     JVMCI_THROW_MSG_NULL(NullPointerException,
2008                          err_msg("Component mirror for array class %s is null", klass->external_name()))
2009   }
2010 
2011   Klass* component_klass = java_lang_Class::as_Klass(component_mirror);
2012   if (component_klass != nullptr) {
2013     JVMCIKlassHandle klass_handle(THREAD, component_klass);
2014     JVMCIObject result = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2015     return JVMCIENV->get_jobject(result);
2016   }
2017   BasicType type = java_lang_Class::primitive_type(component_mirror);
2018   JVMCIObject result = JVMCIENV->get_jvmci_primitive_type(type);
2019   return JVMCIENV->get_jobject(result);
2020 C2V_END
2021 
2022 C2V_VMENTRY(void, ensureInitialized, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2023   Klass* klass = UNPACK_PAIR(Klass, klass);
2024   if (klass == nullptr) {
2025     JVMCI_THROW(NullPointerException);
2026   }
2027   if (klass->should_be_initialized()) {
2028     InstanceKlass* k = InstanceKlass::cast(klass);
2029     k->initialize(CHECK);
2030   }
2031 C2V_END
2032 
2033 C2V_VMENTRY(void, ensureLinked, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2034   CompilerThreadCanCallJava canCallJava(thread, true); // Linking requires Java calls
2035   Klass* klass = UNPACK_PAIR(Klass, klass);
2036   if (klass == nullptr) {
2037     JVMCI_THROW(NullPointerException);
2038   }
2039   if (klass->is_instance_klass()) {
2040     InstanceKlass* k = InstanceKlass::cast(klass);
2041     k->link_class(CHECK);
2042   }
2043 C2V_END
2044 
2045 C2V_VMENTRY_0(jint, interpreterFrameSize, (JNIEnv* env, jobject, jobject bytecode_frame_handle))
2046   if (bytecode_frame_handle == nullptr) {
2047     JVMCI_THROW_0(NullPointerException);
2048   }
2049 
2050   JVMCIObject top_bytecode_frame = JVMCIENV->wrap(bytecode_frame_handle);
2051   JVMCIObject bytecode_frame = top_bytecode_frame;
2052   int size = 0;
2053   int callee_parameters = 0;
2054   int callee_locals = 0;
2055   Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2056   int extra_args = method->max_stack() - JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2057 
2058   while (bytecode_frame.is_non_null()) {
2059     int locks = JVMCIENV->get_BytecodeFrame_numLocks(bytecode_frame);
2060     int temps = JVMCIENV->get_BytecodeFrame_numStack(bytecode_frame);
2061     bool is_top_frame = (JVMCIENV->equals(bytecode_frame, top_bytecode_frame));
2062     Method* method = JVMCIENV->asMethod(JVMCIENV->get_BytecodePosition_method(bytecode_frame));
2063 
2064     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
2065                                                                  temps + callee_parameters,
2066                                                                  extra_args,
2067                                                                  locks,
2068                                                                  callee_parameters,
2069                                                                  callee_locals,
2070                                                                  is_top_frame);
2071     size += frame_size;
2072 
2073     callee_parameters = method->size_of_parameters();
2074     callee_locals = method->max_locals();
2075     extra_args = 0;
2076     bytecode_frame = JVMCIENV->get_BytecodePosition_caller(bytecode_frame);
2077   }
2078   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
2079 C2V_END
2080 
2081 C2V_VMENTRY(void, compileToBytecode, (JNIEnv* env, jobject, jobject lambda_form_handle))
2082   Handle lambda_form = JVMCIENV->asConstant(JVMCIENV->wrap(lambda_form_handle), JVMCI_CHECK);
2083   if (lambda_form->is_a(vmClasses::LambdaForm_klass())) {
2084     TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode");
2085     JavaValue result(T_VOID);
2086     JavaCalls::call_special(&result, lambda_form, vmClasses::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
2087   } else {
2088     JVMCI_THROW_MSG(IllegalArgumentException,
2089                     err_msg("Unexpected type: %s", lambda_form->klass()->external_name()))
2090   }
2091 C2V_END
2092 
2093 C2V_VMENTRY_0(jint, getIdentityHashCode, (JNIEnv* env, jobject, jobject object))
2094   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2095   return obj->identity_hash();
2096 C2V_END
2097 
2098 C2V_VMENTRY_0(jboolean, isInternedString, (JNIEnv* env, jobject, jobject object))
2099   Handle str = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2100   if (!java_lang_String::is_instance(str())) {
2101     return false;
2102   }
2103   int len;
2104   jchar* name = java_lang_String::as_unicode_string(str(), len, CHECK_false);
2105   return (StringTable::lookup(name, len) != nullptr);
2106 C2V_END
2107 
2108 
2109 C2V_VMENTRY_NULL(jobject, unboxPrimitive, (JNIEnv* env, jobject, jobject object))
2110   if (object == nullptr) {
2111     JVMCI_THROW_NULL(NullPointerException);
2112   }
2113   Handle box = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2114   BasicType type = java_lang_boxing_object::basic_type(box());
2115   jvalue result;
2116   if (java_lang_boxing_object::get_value(box(), &result) == T_ILLEGAL) {
2117     return nullptr;
2118   }
2119   JVMCIObject boxResult = JVMCIENV->create_box(type, &result, JVMCI_CHECK_NULL);
2120   return JVMCIENV->get_jobject(boxResult);
2121 C2V_END
2122 
2123 C2V_VMENTRY_NULL(jobject, boxPrimitive, (JNIEnv* env, jobject, jobject object))
2124   if (object == nullptr) {
2125     JVMCI_THROW_NULL(NullPointerException);
2126   }
2127   JVMCIObject box = JVMCIENV->wrap(object);
2128   BasicType type = JVMCIENV->get_box_type(box);
2129   if (type == T_ILLEGAL) {
2130     return nullptr;
2131   }
2132   jvalue value = JVMCIENV->get_boxed_value(type, box);
2133   JavaValue box_result(T_OBJECT);
2134   JavaCallArguments jargs;
2135   Klass* box_klass = nullptr;
2136   Symbol* box_signature = nullptr;
2137 #define BOX_CASE(bt, v, argtype, name)           \
2138   case bt: \
2139     jargs.push_##argtype(value.v); \
2140     box_klass = vmClasses::name##_klass(); \
2141     box_signature = vmSymbols::name##_valueOf_signature(); \
2142     break
2143 
2144   switch (type) {
2145     BOX_CASE(T_BOOLEAN, z, int, Boolean);
2146     BOX_CASE(T_BYTE, b, int, Byte);
2147     BOX_CASE(T_CHAR, c, int, Character);
2148     BOX_CASE(T_SHORT, s, int, Short);
2149     BOX_CASE(T_INT, i, int, Integer);
2150     BOX_CASE(T_LONG, j, long, Long);
2151     BOX_CASE(T_FLOAT, f, float, Float);
2152     BOX_CASE(T_DOUBLE, d, double, Double);
2153     default:
2154       ShouldNotReachHere();
2155   }
2156 #undef BOX_CASE
2157 
2158   JavaCalls::call_static(&box_result,
2159                          box_klass,
2160                          vmSymbols::valueOf_name(),
2161                          box_signature, &jargs, CHECK_NULL);
2162   oop hotspot_box = box_result.get_oop();
2163   JVMCIObject result = JVMCIENV->get_object_constant(hotspot_box, false);
2164   return JVMCIENV->get_jobject(result);
2165 C2V_END
2166 
2167 C2V_VMENTRY_NULL(jobjectArray, getDeclaredConstructors, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2168   Klass* klass = UNPACK_PAIR(Klass, klass);
2169   if (klass == nullptr) {
2170     JVMCI_THROW_NULL(NullPointerException);
2171   }
2172   if (!klass->is_instance_klass()) {
2173     JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2174     return JVMCIENV->get_jobjectArray(methods);
2175   }
2176 
2177   InstanceKlass* iklass = InstanceKlass::cast(klass);
2178   GrowableArray<Method*> constructors_array;
2179   for (int i = 0; i < iklass->methods()->length(); i++) {
2180     Method* m = iklass->methods()->at(i);
2181     if (m->is_object_initializer()) {
2182       constructors_array.append(m);
2183     }
2184   }
2185   JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(constructors_array.length(), JVMCI_CHECK_NULL);
2186   for (int i = 0; i < constructors_array.length(); i++) {
2187     methodHandle ctor(THREAD, constructors_array.at(i));
2188     JVMCIObject method = JVMCIENV->get_jvmci_method(ctor, JVMCI_CHECK_NULL);
2189     JVMCIENV->put_object_at(methods, i, method);
2190   }
2191   return JVMCIENV->get_jobjectArray(methods);
2192 C2V_END
2193 
2194 C2V_VMENTRY_NULL(jobjectArray, getDeclaredMethods, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2195   Klass* klass = UNPACK_PAIR(Klass, klass);
2196   if (klass == nullptr) {
2197     JVMCI_THROW_NULL(NullPointerException);
2198   }
2199   if (!klass->is_instance_klass()) {
2200     JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(0, JVMCI_CHECK_NULL);
2201     return JVMCIENV->get_jobjectArray(methods);
2202   }
2203 
2204   InstanceKlass* iklass = InstanceKlass::cast(klass);
2205   GrowableArray<Method*> methods_array;
2206   for (int i = 0; i < iklass->methods()->length(); i++) {
2207     Method* m = iklass->methods()->at(i);
2208     if (!m->is_object_initializer() && !m->is_static_initializer() && !m->is_overpass()) {
2209       methods_array.append(m);
2210     }
2211   }
2212   JVMCIObjectArray methods = JVMCIENV->new_ResolvedJavaMethod_array(methods_array.length(), JVMCI_CHECK_NULL);
2213   for (int i = 0; i < methods_array.length(); i++) {
2214     methodHandle mh(THREAD, methods_array.at(i));
2215     JVMCIObject method = JVMCIENV->get_jvmci_method(mh, JVMCI_CHECK_NULL);
2216     JVMCIENV->put_object_at(methods, i, method);
2217   }
2218   return JVMCIENV->get_jobjectArray(methods);
2219 C2V_END
2220 
2221 C2V_VMENTRY_NULL(jobjectArray, getDeclaredFieldsInfo, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2222   Klass* klass = UNPACK_PAIR(Klass, klass);
2223   if (klass == nullptr) {
2224     JVMCI_THROW_NULL(NullPointerException);
2225   }
2226   if (!klass->is_instance_klass()) {
2227     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "not an InstanceKlass");
2228   }
2229   InstanceKlass* iklass = InstanceKlass::cast(klass);
2230   int java_fields, injected_fields;
2231   GrowableArray<FieldInfo>* fields = FieldInfoStream::create_FieldInfoArray(iklass->fieldinfo_stream(), &java_fields, &injected_fields);
2232   JVMCIObjectArray array = JVMCIENV->new_FieldInfo_array(fields->length(), JVMCIENV);
2233   for (int i = 0; i < fields->length(); i++) {
2234     JVMCIObject field_info = JVMCIENV->new_FieldInfo(fields->adr_at(i), JVMCI_CHECK_NULL);
2235     JVMCIENV->put_object_at(array, i, field_info);
2236   }
2237   return array.as_jobject();
2238 C2V_END
2239 
2240 static jobject read_field_value(Handle obj, long displacement, jchar type_char, bool is_static, Thread* THREAD, JVMCIEnv* JVMCIENV) {
2241 
2242   BasicType basic_type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_NULL);
2243   int basic_type_elemsize = type2aelembytes(basic_type);
2244   if (displacement < 0 || ((size_t) displacement + basic_type_elemsize > HeapWordSize * obj->size())) {
2245     // Reading outside of the object bounds
2246     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading outside object bounds");
2247   }
2248 
2249   // Perform basic sanity checks on the read.  Primitive reads are permitted to read outside the
2250   // bounds of their fields but object reads must map exactly onto the underlying oop slot.
2251   bool aligned = (displacement % basic_type_elemsize) == 0;
2252   if (!aligned) {
2253     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "read is unaligned");
2254   }
2255   if (basic_type == T_OBJECT) {
2256     if (obj->is_objArray()) {
2257       if (displacement < arrayOopDesc::base_offset_in_bytes(T_OBJECT)) {
2258         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2259       }
2260       if (displacement + heapOopSize > arrayOopDesc::base_offset_in_bytes(T_OBJECT) + arrayOop(obj())->length() * heapOopSize) {
2261         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading after last array element");
2262       }
2263       if (((displacement - arrayOopDesc::base_offset_in_bytes(T_OBJECT)) % heapOopSize) != 0) {
2264         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "misaligned object read from array");
2265       }
2266     } else if (obj->is_instance()) {
2267       InstanceKlass* klass = InstanceKlass::cast(is_static ? java_lang_Class::as_Klass(obj()) : obj->klass());
2268       fieldDescriptor fd;
2269       if (!klass->find_field_from_offset(displacement, is_static, &fd)) {
2270         JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Can't find field at displacement %d in object of type %s", (int) displacement, klass->external_name()));
2271       }
2272       if (fd.field_type() != T_OBJECT && fd.field_type() != T_ARRAY) {
2273         JVMCI_THROW_MSG_NULL(IllegalArgumentException, err_msg("Field at displacement %d in object of type %s is %s but expected %s", (int) displacement,
2274                                                                klass->external_name(), type2name(fd.field_type()), type2name(basic_type)));
2275       }
2276     } else if (obj->is_typeArray()) {
2277       JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Can't read objects from primitive array");
2278     } else {
2279       ShouldNotReachHere();
2280     }
2281   } else {
2282     if (obj->is_objArray()) {
2283       JVMCI_THROW_MSG_NULL(IllegalArgumentException, "Reading primitive from object array");
2284     } else if (obj->is_typeArray()) {
2285       if (displacement < arrayOopDesc::base_offset_in_bytes(ArrayKlass::cast(obj->klass())->element_type())) {
2286         JVMCI_THROW_MSG_NULL(IllegalArgumentException, "reading from array header");
2287       }
2288     }
2289   }
2290 
2291   jlong value = 0;
2292 
2293   // Treat all reads as volatile for simplicity as this function can be used
2294   // both for reading Java fields declared as volatile as well as for constant
2295   // folding Unsafe.get* methods with volatile semantics.
2296 
2297   switch (basic_type) {
2298     case T_BOOLEAN: value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jboolean>(displacement)); break;
2299     case T_BYTE:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jbyte>(displacement));    break;
2300     case T_SHORT:   value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jshort>(displacement));   break;
2301     case T_CHAR:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jchar>(displacement));    break;
2302     case T_FLOAT:
2303     case T_INT:     value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jint>(displacement));     break;
2304     case T_DOUBLE:
2305     case T_LONG:    value = HeapAccess<MO_SEQ_CST>::load(obj->field_addr<jlong>(displacement));    break;
2306 
2307     case T_OBJECT: {
2308       if (displacement == java_lang_Class::component_mirror_offset() && java_lang_Class::is_instance(obj()) &&
2309           (java_lang_Class::as_Klass(obj()) == nullptr || !java_lang_Class::as_Klass(obj())->is_array_klass())) {
2310         // Class.componentType for non-array classes can transiently contain an int[] that's
2311         // used for locking so always return null to mimic Class.getComponentType()
2312         return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2313       }
2314 
2315       // Perform the read including any barriers required to make the reference strongly reachable
2316       // since it will be wrapped as a JavaConstant.
2317       oop value = obj->obj_field_access<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>(displacement);
2318 
2319       if (value == nullptr) {
2320         return JVMCIENV->get_jobject(JVMCIENV->get_JavaConstant_NULL_POINTER());
2321       } else {
2322         if (value != nullptr && !oopDesc::is_oop(value)) {
2323           // Throw an exception to improve debuggability.  This check isn't totally reliable because
2324           // is_oop doesn't try to be completety safe but for most invalid values it provides a good
2325           // enough answer.  It possible to crash in the is_oop call but that just means the crash happens
2326           // closer to where things went wrong.
2327           JVMCI_THROW_MSG_NULL(InternalError, err_msg("Read bad oop " INTPTR_FORMAT " at offset " JLONG_FORMAT " in object " INTPTR_FORMAT " of type %s",
2328                                                       p2i(value), displacement, p2i(obj()), obj->klass()->external_name()));
2329         }
2330 
2331         JVMCIObject result = JVMCIENV->get_object_constant(value);
2332         return JVMCIENV->get_jobject(result);
2333       }
2334     }
2335 
2336     default:
2337       ShouldNotReachHere();
2338   }
2339   JVMCIObject result = JVMCIENV->call_JavaConstant_forPrimitive(type_char, value, JVMCI_CHECK_NULL);
2340   return JVMCIENV->get_jobject(result);
2341 }
2342 
2343 C2V_VMENTRY_NULL(jobject, readStaticFieldValue, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), long displacement, jchar type_char))
2344   Klass* klass = UNPACK_PAIR(Klass, klass);
2345   Handle obj(THREAD, klass->java_mirror());
2346   return read_field_value(obj, displacement, type_char, true, THREAD, JVMCIENV);
2347 C2V_END
2348 
2349 C2V_VMENTRY_NULL(jobject, readFieldValue, (JNIEnv* env, jobject, jobject object, ARGUMENT_PAIR(expected_type), long displacement, jchar type_char))
2350   if (object == nullptr) {
2351     JVMCI_THROW_NULL(NullPointerException);
2352   }
2353 
2354   // asConstant will throw an NPE if a constant contains null
2355   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2356 
2357   Klass* expected_klass = UNPACK_PAIR(Klass, expected_type);
2358   if (expected_klass != nullptr) {
2359     InstanceKlass* expected_iklass = InstanceKlass::cast(expected_klass);
2360     if (!obj->is_a(expected_iklass)) {
2361       // Not of the expected type
2362       return nullptr;
2363     }
2364   }
2365   bool is_static = expected_klass == nullptr && java_lang_Class::is_instance(obj()) && displacement >= InstanceMirrorKlass::offset_of_static_fields();
2366   return read_field_value(obj, displacement, type_char, is_static, THREAD, JVMCIENV);
2367 C2V_END
2368 
2369 C2V_VMENTRY_0(jboolean, isInstance, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jobject object))
2370   Klass* klass = UNPACK_PAIR(Klass, klass);
2371   if (object == nullptr || klass == nullptr) {
2372     JVMCI_THROW_0(NullPointerException);
2373   }
2374   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_0);
2375   return obj->is_a(klass);
2376 C2V_END
2377 
2378 C2V_VMENTRY_0(jboolean, isAssignableFrom, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), ARGUMENT_PAIR(subklass)))
2379   Klass* klass = UNPACK_PAIR(Klass, klass);
2380   Klass* subklass = UNPACK_PAIR(Klass, subklass);
2381   if (klass == nullptr || subklass == nullptr) {
2382     JVMCI_THROW_0(NullPointerException);
2383   }
2384   return subklass->is_subtype_of(klass);
2385 C2V_END
2386 
2387 C2V_VMENTRY_0(jboolean, isTrustedForIntrinsics, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2388   Klass* klass = UNPACK_PAIR(Klass, klass);
2389   if (klass == nullptr) {
2390     JVMCI_THROW_0(NullPointerException);
2391   }
2392   InstanceKlass* ik = InstanceKlass::cast(klass);
2393   if (ik->class_loader_data()->is_boot_class_loader_data() || ik->class_loader_data()->is_platform_class_loader_data()) {
2394     return true;
2395   }
2396   return false;
2397 C2V_END
2398 
2399 C2V_VMENTRY_NULL(jobject, asJavaType, (JNIEnv* env, jobject, jobject object))
2400   if (object == nullptr) {
2401     JVMCI_THROW_NULL(NullPointerException);
2402   }
2403   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2404   if (java_lang_Class::is_instance(obj())) {
2405     if (java_lang_Class::is_primitive(obj())) {
2406       JVMCIObject type = JVMCIENV->get_jvmci_primitive_type(java_lang_Class::primitive_type(obj()));
2407       return JVMCIENV->get_jobject(type);
2408     }
2409     Klass* klass = java_lang_Class::as_Klass(obj());
2410     JVMCIKlassHandle klass_handle(THREAD);
2411     klass_handle = klass;
2412     JVMCIObject type = JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_NULL);
2413     return JVMCIENV->get_jobject(type);
2414   }
2415   return nullptr;
2416 C2V_END
2417 
2418 
2419 C2V_VMENTRY_NULL(jobject, asString, (JNIEnv* env, jobject, jobject object))
2420   if (object == nullptr) {
2421     JVMCI_THROW_NULL(NullPointerException);
2422   }
2423   Handle obj = JVMCIENV->asConstant(JVMCIENV->wrap(object), JVMCI_CHECK_NULL);
2424   const char* str = java_lang_String::as_utf8_string(obj());
2425   JVMCIObject result = JVMCIENV->create_string(str, JVMCI_CHECK_NULL);
2426   return JVMCIENV->get_jobject(result);
2427 C2V_END
2428 
2429 
2430 C2V_VMENTRY_0(jboolean, equals, (JNIEnv* env, jobject, jobject x, jlong xHandle, jobject y, jlong yHandle))
2431   if (x == nullptr || y == nullptr) {
2432     JVMCI_THROW_0(NullPointerException);
2433   }
2434   return JVMCIENV->resolve_oop_handle(xHandle) == JVMCIENV->resolve_oop_handle(yHandle);
2435 C2V_END
2436 
2437 C2V_VMENTRY_NULL(jobject, getJavaMirror, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass)))
2438   Klass* klass = UNPACK_PAIR(Klass, klass);
2439   if (klass == nullptr) {
2440     JVMCI_THROW_NULL(NullPointerException);
2441   }
2442   Handle mirror(THREAD, klass->java_mirror());
2443   JVMCIObject result = JVMCIENV->get_object_constant(mirror());
2444   return JVMCIENV->get_jobject(result);
2445 C2V_END
2446 
2447 
2448 C2V_VMENTRY_0(jint, getArrayLength, (JNIEnv* env, jobject, jobject x))
2449   if (x == nullptr) {
2450     JVMCI_THROW_0(NullPointerException);
2451   }
2452   Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_0);
2453   if (xobj->klass()->is_array_klass()) {
2454     return arrayOop(xobj())->length();
2455   }
2456   return -1;
2457  C2V_END
2458 
2459 
2460 C2V_VMENTRY_NULL(jobject, readArrayElement, (JNIEnv* env, jobject, jobject x, int index))
2461   if (x == nullptr) {
2462     JVMCI_THROW_NULL(NullPointerException);
2463   }
2464   Handle xobj = JVMCIENV->asConstant(JVMCIENV->wrap(x), JVMCI_CHECK_NULL);
2465   if (xobj->klass()->is_array_klass()) {
2466     arrayOop array = arrayOop(xobj());
2467     BasicType element_type = ArrayKlass::cast(array->klass())->element_type();
2468     if (index < 0 || index >= array->length()) {
2469       return nullptr;
2470     }
2471     JVMCIObject result;
2472 
2473     if (element_type == T_OBJECT) {
2474       result = JVMCIENV->get_object_constant(objArrayOop(xobj())->obj_at(index));
2475       if (result.is_null()) {
2476         result = JVMCIENV->get_JavaConstant_NULL_POINTER();
2477       }
2478     } else {
2479       jvalue value;
2480       switch (element_type) {
2481         case T_DOUBLE:        value.d = typeArrayOop(xobj())->double_at(index);        break;
2482         case T_FLOAT:         value.f = typeArrayOop(xobj())->float_at(index);         break;
2483         case T_LONG:          value.j = typeArrayOop(xobj())->long_at(index);          break;
2484         case T_INT:           value.i = typeArrayOop(xobj())->int_at(index);            break;
2485         case T_SHORT:         value.s = typeArrayOop(xobj())->short_at(index);          break;
2486         case T_CHAR:          value.c = typeArrayOop(xobj())->char_at(index);           break;
2487         case T_BYTE:          value.b = typeArrayOop(xobj())->byte_at(index);           break;
2488         case T_BOOLEAN:       value.z = typeArrayOop(xobj())->byte_at(index) & 1;       break;
2489         default:              ShouldNotReachHere();
2490       }
2491       result = JVMCIENV->create_box(element_type, &value, JVMCI_CHECK_NULL);
2492     }
2493     assert(!result.is_null(), "must have a value");
2494     return JVMCIENV->get_jobject(result);
2495   }
2496   return nullptr;;
2497 C2V_END
2498 
2499 
2500 C2V_VMENTRY_0(jint, arrayBaseOffset, (JNIEnv* env, jobject, jchar type_char))
2501   BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2502   return arrayOopDesc::base_offset_in_bytes(type);
2503 C2V_END
2504 
2505 C2V_VMENTRY_0(jint, arrayIndexScale, (JNIEnv* env, jobject, jchar type_char))
2506   BasicType type = JVMCIENV->typeCharToBasicType(type_char, JVMCI_CHECK_0);
2507   return type2aelembytes(type);
2508 C2V_END
2509 
2510 C2V_VMENTRY(void, clearOopHandle, (JNIEnv* env, jobject, jlong oop_handle))
2511   if (oop_handle == 0L) {
2512     JVMCI_THROW(NullPointerException);
2513   }
2514   // Assert before nulling out, for better debugging.
2515   assert(JVMCIRuntime::is_oop_handle(oop_handle), "precondition");
2516   oop* oop_ptr = (oop*) oop_handle;
2517   NativeAccess<>::oop_store(oop_ptr, (oop) nullptr);
2518 C2V_END
2519 
2520 C2V_VMENTRY(void, releaseClearedOopHandles, (JNIEnv* env, jobject))
2521   JVMCIENV->runtime()->release_cleared_oop_handles();
2522 C2V_END
2523 
2524 static void requireJVMCINativeLibrary(JVMCI_TRAPS) {
2525   if (!UseJVMCINativeLibrary) {
2526     JVMCI_THROW_MSG(UnsupportedOperationException, "JVMCI shared library is not enabled (requires -XX:+UseJVMCINativeLibrary)");
2527   }
2528 }
2529 
2530 C2V_VMENTRY_NULL(jlongArray, registerNativeMethods, (JNIEnv* env, jobject, jclass mirror))
2531   requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2532   requireInHotSpot("registerNativeMethods", JVMCI_CHECK_NULL);
2533   char* sl_path;
2534   void* sl_handle;
2535   JVMCIRuntime* runtime;
2536   {
2537     // Ensure the JVMCI shared library runtime is initialized.
2538     PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2539     PEER_JVMCIENV->check_init(JVMCI_CHECK_NULL);
2540 
2541     HandleMark hm(THREAD);
2542     runtime = JVMCI::compiler_runtime(thread);
2543     if (PEER_JVMCIENV->has_pending_exception()) {
2544       PEER_JVMCIENV->describe_pending_exception(tty);
2545     }
2546     sl_handle = JVMCI::get_shared_library(sl_path, false);
2547     if (sl_handle == nullptr) {
2548       JVMCI_THROW_MSG_NULL(InternalError, err_msg("Error initializing JVMCI runtime %d", runtime->id()));
2549     }
2550   }
2551 
2552   if (mirror == nullptr) {
2553     JVMCI_THROW_NULL(NullPointerException);
2554   }
2555   Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2556   if (klass == nullptr || !klass->is_instance_klass()) {
2557     JVMCI_THROW_MSG_NULL(IllegalArgumentException, "clazz is for primitive type");
2558   }
2559 
2560   InstanceKlass* iklass = InstanceKlass::cast(klass);
2561   for (int i = 0; i < iklass->methods()->length(); i++) {
2562     methodHandle method(THREAD, iklass->methods()->at(i));
2563     if (method->is_native()) {
2564 
2565       // Compute argument size
2566       int args_size = 1                             // JNIEnv
2567                     + (method->is_static() ? 1 : 0) // class for static methods
2568                     + method->size_of_parameters(); // actual parameters
2569 
2570       // 1) Try JNI short style
2571       stringStream st;
2572       char* pure_name = NativeLookup::pure_jni_name(method);
2573       guarantee(pure_name != nullptr, "Illegal native method name encountered");
2574       os::print_jni_name_prefix_on(&st, args_size);
2575       st.print_raw(pure_name);
2576       os::print_jni_name_suffix_on(&st, args_size);
2577       char* jni_name = st.as_string();
2578 
2579       address entry = (address) os::dll_lookup(sl_handle, jni_name);
2580       if (entry == nullptr) {
2581         // 2) Try JNI long style
2582         st.reset();
2583         char* long_name = NativeLookup::long_jni_name(method);
2584         guarantee(long_name != nullptr, "Illegal native method name encountered");
2585         os::print_jni_name_prefix_on(&st, args_size);
2586         st.print_raw(pure_name);
2587         st.print_raw(long_name);
2588         os::print_jni_name_suffix_on(&st, args_size);
2589         char* jni_long_name = st.as_string();
2590         entry = (address) os::dll_lookup(sl_handle, jni_long_name);
2591         if (entry == nullptr) {
2592           JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [neither %s nor %s exist in %s]",
2593               method->name_and_sig_as_C_string(),
2594               jni_name, jni_long_name, sl_path));
2595         }
2596       }
2597 
2598       if (method->has_native_function() && entry != method->native_function()) {
2599         JVMCI_THROW_MSG_NULL(UnsatisfiedLinkError, err_msg("%s [cannot re-link from " PTR_FORMAT " to " PTR_FORMAT "]",
2600             method->name_and_sig_as_C_string(), p2i(method->native_function()), p2i(entry)));
2601       }
2602       method->set_native_function(entry, Method::native_bind_event_is_interesting);
2603       log_debug(jni, resolve)("[Dynamic-linking native method %s.%s ... JNI] @ " PTR_FORMAT,
2604                               method->method_holder()->external_name(),
2605                               method->name()->as_C_string(),
2606                               p2i((void*) entry));
2607     }
2608   }
2609 
2610   typeArrayOop info_oop = oopFactory::new_longArray(4, CHECK_NULL);
2611   jlongArray info = (jlongArray) JNIHandles::make_local(THREAD, info_oop);
2612   runtime->init_JavaVM_info(info, JVMCI_CHECK_NULL);
2613   return info;
2614 C2V_END
2615 
2616 C2V_VMENTRY_PREFIX(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject c2vm))
2617   if (thread == nullptr || thread->libjvmci_runtime() == nullptr) {
2618     // Called from unattached JVMCI shared library thread
2619     return false;
2620   }
2621   if (thread->jni_environment() == env) {
2622     C2V_BLOCK(jboolean, isCurrentThreadAttached, (JNIEnv* env, jobject))
2623     JVMCITraceMark jtm("isCurrentThreadAttached");
2624     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2625     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2626     if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2627       JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in isCurrentThreadAttached");
2628     }
2629     JNIEnv* peerEnv;
2630     return runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) == JNI_OK;
2631   }
2632   return true;
2633 C2V_END
2634 
2635 C2V_VMENTRY_PREFIX(jlong, getCurrentJavaThread, (JNIEnv* env, jobject c2vm))
2636   if (thread == nullptr) {
2637     // Called from unattached JVMCI shared library thread
2638     return 0L;
2639   }
2640   return (jlong) p2i(thread);
2641 C2V_END
2642 
2643 // Attaches a thread started in a JVMCI shared library to a JavaThread and JVMCI runtime.
2644 static void attachSharedLibraryThread(JNIEnv* env, jbyteArray name, jboolean as_daemon) {
2645   JavaVM* javaVM = nullptr;
2646   jint res = env->GetJavaVM(&javaVM);
2647   if (res != JNI_OK) {
2648     JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Error getting shared library JavaVM from shared library JNIEnv: %d", res));
2649   }
2650   extern struct JavaVM_ main_vm;
2651   JNIEnv* hotspotEnv;
2652 
2653   int name_len = env->GetArrayLength(name);
2654   char name_buf[64]; // Cannot use Resource heap as it requires a current thread
2655   int to_copy = MIN2(name_len, (int) sizeof(name_buf) - 1);
2656   env->GetByteArrayRegion(name, 0, to_copy, (jbyte*) name_buf);
2657   name_buf[to_copy] = '\0';
2658   JavaVMAttachArgs attach_args;
2659   attach_args.version = JNI_VERSION_1_2;
2660   attach_args.name = name_buf;
2661   attach_args.group = nullptr;
2662   res = as_daemon ? main_vm.AttachCurrentThreadAsDaemon((void**)&hotspotEnv, &attach_args) :
2663                     main_vm.AttachCurrentThread((void**)&hotspotEnv, &attach_args);
2664   if (res != JNI_OK) {
2665     JNI_THROW("attachSharedLibraryThread", InternalError, err_msg("Trying to attach thread returned %d", res));
2666   }
2667   JavaThread* thread = JavaThread::thread_from_jni_environment(hotspotEnv);
2668   const char* attach_error;
2669   {
2670     // Transition to VM
2671     JVMCI_VM_ENTRY_MARK
2672     attach_error = JVMCIRuntime::attach_shared_library_thread(thread, javaVM);
2673     // Transition back to Native
2674   }
2675   if (attach_error != nullptr) {
2676     JNI_THROW("attachCurrentThread", InternalError, attach_error);
2677   }
2678 }
2679 
2680 C2V_VMENTRY_PREFIX(jboolean, attachCurrentThread, (JNIEnv* env, jobject c2vm, jbyteArray name, jboolean as_daemon, jlongArray javaVM_info))
2681   if (thread == nullptr) {
2682     attachSharedLibraryThread(env, name, as_daemon);
2683     return true;
2684   }
2685   if (thread->jni_environment() == env) {
2686     // Called from HotSpot
2687     C2V_BLOCK(jboolean, attachCurrentThread, (JNIEnv* env, jobject, jboolean))
2688     JVMCITraceMark jtm("attachCurrentThread");
2689     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2690 
2691     JVMCIRuntime* runtime = JVMCI::compiler_runtime(thread);
2692     JNIEnv* peerJNIEnv;
2693     if (runtime->has_shared_library_javavm()) {
2694       if (runtime->GetEnv(thread, (void**)&peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2695         // Already attached
2696         runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2697         return false;
2698       }
2699     }
2700 
2701     {
2702       // Ensure the JVMCI shared library runtime is initialized.
2703       PEER_JVMCIENV_FROM_THREAD(THREAD, false);
2704       PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2705 
2706       HandleMark hm(thread);
2707       JVMCIObject receiver = runtime->get_HotSpotJVMCIRuntime(PEER_JVMCIENV);
2708       if (PEER_JVMCIENV->has_pending_exception()) {
2709         PEER_JVMCIENV->describe_pending_exception(tty);
2710       }
2711       char* sl_path;
2712       if (JVMCI::get_shared_library(sl_path, false) == nullptr) {
2713         JVMCI_THROW_MSG_0(InternalError, "Error initializing JVMCI runtime");
2714       }
2715     }
2716 
2717     JavaVMAttachArgs attach_args;
2718     attach_args.version = JNI_VERSION_1_2;
2719     attach_args.name = const_cast<char*>(thread->name());
2720     attach_args.group = nullptr;
2721     if (runtime->GetEnv(thread, (void**) &peerJNIEnv, JNI_VERSION_1_2) == JNI_OK) {
2722       return false;
2723     }
2724     jint res = as_daemon ? runtime->AttachCurrentThreadAsDaemon(thread, (void**) &peerJNIEnv, &attach_args) :
2725                            runtime->AttachCurrentThread(thread, (void**) &peerJNIEnv, &attach_args);
2726 
2727     if (res == JNI_OK) {
2728       guarantee(peerJNIEnv != nullptr, "must be");
2729       runtime->init_JavaVM_info(javaVM_info, JVMCI_CHECK_0);
2730       JVMCI_event_1("attached to JavaVM[%d] for JVMCI runtime %d", runtime->get_shared_library_javavm_id(), runtime->id());
2731       return true;
2732     }
2733     JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, attach_args.name));
2734   }
2735   // Called from JVMCI shared library
2736   return false;
2737 C2V_END
2738 
2739 C2V_VMENTRY_PREFIX(jboolean, detachCurrentThread, (JNIEnv* env, jobject c2vm, jboolean release))
2740   if (thread == nullptr) {
2741     // Called from unattached JVMCI shared library thread
2742     JNI_THROW_("detachCurrentThread", IllegalStateException, "Cannot detach non-attached thread", false);
2743   }
2744   if (thread->jni_environment() == env) {
2745     // Called from HotSpot
2746     C2V_BLOCK(void, detachCurrentThread, (JNIEnv* env, jobject))
2747     JVMCITraceMark jtm("detachCurrentThread");
2748     requireJVMCINativeLibrary(JVMCI_CHECK_0);
2749     requireInHotSpot("detachCurrentThread", JVMCI_CHECK_0);
2750     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2751     if (runtime == nullptr || !runtime->has_shared_library_javavm()) {
2752       JVMCI_THROW_MSG_0(IllegalStateException, "Require JVMCI shared library JavaVM to be initialized in detachCurrentThread");
2753     }
2754     JNIEnv* peerEnv;
2755 
2756     if (runtime->GetEnv(thread, (void**) &peerEnv, JNI_VERSION_1_2) != JNI_OK) {
2757       JVMCI_THROW_MSG_0(IllegalStateException, err_msg("Cannot detach non-attached thread: %s", thread->name()));
2758     }
2759     jint res = runtime->DetachCurrentThread(thread);
2760     if (res != JNI_OK) {
2761       JVMCI_THROW_MSG_0(InternalError, err_msg("Error %d while attaching %s", res, thread->name()));
2762     }
2763     JVMCI_event_1("detached from JavaVM[%d] for JVMCI runtime %d",
2764         runtime->get_shared_library_javavm_id(), runtime->id());
2765     if (release) {
2766       return runtime->detach_thread(thread, "user thread detach");
2767     }
2768   } else {
2769     // Called from attached JVMCI shared library thread
2770     if (release) {
2771       JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread cannot release JVMCI shared library JavaVM", false);
2772     }
2773     JVMCIRuntime* runtime = thread->libjvmci_runtime();
2774     if (runtime == nullptr) {
2775       JNI_THROW_("detachCurrentThread", InternalError, "JVMCI shared library thread should have a JVMCI runtime", false);
2776     }
2777     {
2778       // Transition to VM
2779       C2V_BLOCK(jboolean, detachCurrentThread, (JNIEnv* env, jobject))
2780       // Cannot destroy shared library JavaVM as we're about to return to it.
2781       runtime->detach_thread(thread, "shared library thread detach", false);
2782       JVMCI_event_1("detaching JVMCI shared library thread from HotSpot JavaVM");
2783       // Transition back to Native
2784     }
2785     extern struct JavaVM_ main_vm;
2786     jint res = main_vm.DetachCurrentThread();
2787     if (res != JNI_OK) {
2788       JNI_THROW_("detachCurrentThread", InternalError, "Cannot detach non-attached thread", false);
2789     }
2790   }
2791   return false;
2792 C2V_END
2793 
2794 C2V_VMENTRY_0(jlong, translate, (JNIEnv* env, jobject, jobject obj_handle, jboolean callPostTranslation))
2795   requireJVMCINativeLibrary(JVMCI_CHECK_0);
2796   if (obj_handle == nullptr) {
2797     return 0L;
2798   }
2799   PEER_JVMCIENV_FROM_THREAD(THREAD, !JVMCIENV->is_hotspot());
2800   CompilerThreadCanCallJava canCallJava(thread, PEER_JVMCIENV->is_hotspot());
2801   PEER_JVMCIENV->check_init(JVMCI_CHECK_0);
2802 
2803   JVMCIEnv* thisEnv = JVMCIENV;
2804   JVMCIObject obj = thisEnv->wrap(obj_handle);
2805   JVMCIObject result;
2806   if (thisEnv->isa_HotSpotResolvedJavaMethodImpl(obj)) {
2807     methodHandle method(THREAD, thisEnv->asMethod(obj));
2808     result = PEER_JVMCIENV->get_jvmci_method(method, JVMCI_CHECK_0);
2809   } else if (thisEnv->isa_HotSpotResolvedObjectTypeImpl(obj)) {
2810     Klass* klass = thisEnv->asKlass(obj);
2811     JVMCIKlassHandle klass_handle(THREAD);
2812     klass_handle = klass;
2813     result = PEER_JVMCIENV->get_jvmci_type(klass_handle, JVMCI_CHECK_0);
2814   } else if (thisEnv->isa_HotSpotResolvedPrimitiveType(obj)) {
2815     BasicType type = JVMCIENV->kindToBasicType(JVMCIENV->get_HotSpotResolvedPrimitiveType_kind(obj), JVMCI_CHECK_0);
2816     result = PEER_JVMCIENV->get_jvmci_primitive_type(type);
2817   } else if (thisEnv->isa_IndirectHotSpotObjectConstantImpl(obj) ||
2818              thisEnv->isa_DirectHotSpotObjectConstantImpl(obj)) {
2819     Handle constant = thisEnv->asConstant(obj, JVMCI_CHECK_0);
2820     result = PEER_JVMCIENV->get_object_constant(constant());
2821   } else if (thisEnv->isa_HotSpotNmethod(obj)) {
2822     if (PEER_JVMCIENV->is_hotspot()) {
2823       JVMCINMethodHandle nmethod_handle(THREAD);
2824       nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2825       if (nm != nullptr) {
2826         JVMCINMethodData* data = nm->jvmci_nmethod_data();
2827         if (data != nullptr) {
2828           // Only the mirror in the HotSpot heap is accessible
2829           // through JVMCINMethodData
2830           oop nmethod_mirror = data->get_nmethod_mirror(nm, /* phantom_ref */ true);
2831           if (nmethod_mirror != nullptr) {
2832             result = HotSpotJVMCI::wrap(nmethod_mirror);
2833           }
2834         }
2835       }
2836     }
2837 
2838     if (result.is_null()) {
2839       JVMCIObject methodObject = thisEnv->get_HotSpotNmethod_method(obj);
2840       methodHandle mh(THREAD, thisEnv->asMethod(methodObject));
2841       jboolean isDefault = thisEnv->get_HotSpotNmethod_isDefault(obj);
2842       jlong compileIdSnapshot = thisEnv->get_HotSpotNmethod_compileIdSnapshot(obj);
2843       JVMCIObject name_string = thisEnv->get_InstalledCode_name(obj);
2844       const char* cstring = name_string.is_null() ? nullptr : thisEnv->as_utf8_string(name_string);
2845       // Create a new HotSpotNmethod instance in the peer runtime
2846       result = PEER_JVMCIENV->new_HotSpotNmethod(mh, cstring, isDefault, compileIdSnapshot, JVMCI_CHECK_0);
2847       JVMCINMethodHandle nmethod_handle(THREAD);
2848       nmethod* nm = JVMCIENV->get_nmethod(obj, nmethod_handle);
2849       if (result.is_null()) {
2850         // exception occurred (e.g. OOME) creating a new HotSpotNmethod
2851       } else if (nm == nullptr) {
2852         // nmethod must have been unloaded
2853       } else {
2854         // Link the new HotSpotNmethod to the nmethod
2855         PEER_JVMCIENV->initialize_installed_code(result, nm, JVMCI_CHECK_0);
2856         // Only non-default HotSpotNmethod instances in the HotSpot heap are tracked directly by the runtime.
2857         if (!isDefault && PEER_JVMCIENV->is_hotspot()) {
2858           JVMCINMethodData* data = nm->jvmci_nmethod_data();
2859           if (data == nullptr) {
2860             JVMCI_THROW_MSG_0(IllegalArgumentException, "Missing HotSpotNmethod data");
2861           }
2862           if (data->get_nmethod_mirror(nm, /* phantom_ref */ false) != nullptr) {
2863             JVMCI_THROW_MSG_0(IllegalArgumentException, "Cannot overwrite existing HotSpotNmethod mirror for nmethod");
2864           }
2865           oop nmethod_mirror = HotSpotJVMCI::resolve(result);
2866           data->set_nmethod_mirror(nm, nmethod_mirror);
2867         }
2868       }
2869     }
2870   } else {
2871     JVMCI_THROW_MSG_0(IllegalArgumentException,
2872                 err_msg("Cannot translate object of type: %s", thisEnv->klass_name(obj)));
2873   }
2874   if (callPostTranslation) {
2875     PEER_JVMCIENV->call_HotSpotJVMCIRuntime_postTranslation(result, JVMCI_CHECK_0);
2876   }
2877   // Propagate any exception that occurred while creating the translated object
2878   if (PEER_JVMCIENV->transfer_pending_exception(thread, thisEnv)) {
2879     return 0L;
2880   }
2881   return (jlong) PEER_JVMCIENV->make_global(result).as_jobject();
2882 C2V_END
2883 
2884 C2V_VMENTRY_NULL(jobject, unhand, (JNIEnv* env, jobject, jlong obj_handle))
2885   requireJVMCINativeLibrary(JVMCI_CHECK_NULL);
2886   if (obj_handle == 0L) {
2887     return nullptr;
2888   }
2889   jobject global_handle = (jobject) obj_handle;
2890   JVMCIObject global_handle_obj = JVMCIENV->wrap(global_handle);
2891   jobject result = JVMCIENV->make_local(global_handle_obj).as_jobject();
2892 
2893   JVMCIENV->destroy_global(global_handle_obj);
2894   return result;
2895 C2V_END
2896 
2897 C2V_VMENTRY(void, updateHotSpotNmethod, (JNIEnv* env, jobject, jobject code_handle))
2898   JVMCIObject code = JVMCIENV->wrap(code_handle);
2899   // Execute this operation for the side effect of updating the InstalledCode state
2900   JVMCINMethodHandle nmethod_handle(THREAD);
2901   JVMCIENV->get_nmethod(code, nmethod_handle);
2902 C2V_END
2903 
2904 C2V_VMENTRY_NULL(jbyteArray, getCode, (JNIEnv* env, jobject, jobject code_handle))
2905   JVMCIObject code = JVMCIENV->wrap(code_handle);
2906   CodeBlob* cb = JVMCIENV->get_code_blob(code);
2907   if (cb == nullptr) {
2908     return nullptr;
2909   }
2910   // Make a resource copy of code before the allocation causes a safepoint
2911   int code_size = cb->code_size();
2912   jbyte* code_bytes = NEW_RESOURCE_ARRAY(jbyte, code_size);
2913   memcpy(code_bytes, (jbyte*) cb->code_begin(), code_size);
2914 
2915   JVMCIPrimitiveArray result = JVMCIENV->new_byteArray(code_size, JVMCI_CHECK_NULL);
2916   JVMCIENV->copy_bytes_from(code_bytes, result, 0, code_size);
2917   return JVMCIENV->get_jbyteArray(result);
2918 C2V_END
2919 
2920 C2V_VMENTRY_NULL(jobject, asReflectionExecutable, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
2921   requireInHotSpot("asReflectionExecutable", JVMCI_CHECK_NULL);
2922   methodHandle m(THREAD, UNPACK_PAIR(Method, method));
2923   oop executable;
2924   if (m->is_object_initializer()) {
2925     executable = Reflection::new_constructor(m, CHECK_NULL);
2926   } else if (m->is_static_initializer()) {
2927     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2928         "Cannot create java.lang.reflect.Method for class initializer");
2929   } else {
2930     executable = Reflection::new_method(m, false, CHECK_NULL);
2931   }
2932   return JNIHandles::make_local(THREAD, executable);
2933 C2V_END
2934 
2935 static InstanceKlass* check_field(Klass* klass, jint index, JVMCI_TRAPS) {
2936   if (!klass->is_instance_klass()) {
2937     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2938         err_msg("Expected non-primitive type, got %s", klass->external_name()));
2939   }
2940   InstanceKlass* iklass = InstanceKlass::cast(klass);
2941   if (index < 0 || index > iklass->total_fields_count()) {
2942     JVMCI_THROW_MSG_NULL(IllegalArgumentException,
2943         err_msg("Field index %d out of bounds for %s", index, klass->external_name()));
2944   }
2945   return iklass;
2946 }
2947 
2948 C2V_VMENTRY_NULL(jobject, asReflectionField, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index))
2949   requireInHotSpot("asReflectionField", JVMCI_CHECK_NULL);
2950   Klass* klass = UNPACK_PAIR(Klass, klass);
2951   InstanceKlass* iklass = check_field(klass, index, JVMCIENV);
2952   fieldDescriptor fd(iklass, index);
2953   oop reflected = Reflection::new_field(&fd, CHECK_NULL);
2954   return JNIHandles::make_local(THREAD, reflected);
2955 C2V_END
2956 
2957 static jbyteArray get_encoded_annotation_data(InstanceKlass* holder, AnnotationArray* annotations_array, bool for_class,
2958                                               jint filter_length, jlong filter_klass_pointers,
2959                                               JavaThread* THREAD, JVMCIEnv* JVMCIENV) {
2960   // Get a ConstantPool object for annotation parsing
2961   Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
2962   reflect_ConstantPool::set_cp(jcp(), holder->constants());
2963 
2964   // load VMSupport
2965   Symbol* klass = vmSymbols::jdk_internal_vm_VMSupport();
2966   Klass* k = SystemDictionary::resolve_or_fail(klass, true, CHECK_NULL);
2967 
2968   InstanceKlass* vm_support = InstanceKlass::cast(k);
2969   if (vm_support->should_be_initialized()) {
2970     vm_support->initialize(CHECK_NULL);
2971   }
2972 
2973   typeArrayOop annotations_oop = Annotations::make_java_array(annotations_array, CHECK_NULL);
2974   typeArrayHandle annotations = typeArrayHandle(THREAD, annotations_oop);
2975 
2976   InstanceKlass** filter = filter_length == 1 ?
2977       (InstanceKlass**) &filter_klass_pointers:
2978       (InstanceKlass**) filter_klass_pointers;
2979   objArrayOop filter_oop = oopFactory::new_objArray(vmClasses::Class_klass(), filter_length, CHECK_NULL);
2980   objArrayHandle filter_classes(THREAD, filter_oop);
2981   for (int i = 0; i < filter_length; i++) {
2982     filter_classes->obj_at_put(i, filter[i]->java_mirror());
2983   }
2984 
2985   // invoke VMSupport.encodeAnnotations
2986   JavaValue result(T_OBJECT);
2987   JavaCallArguments args;
2988   args.push_oop(annotations);
2989   args.push_oop(Handle(THREAD, holder->java_mirror()));
2990   args.push_oop(jcp);
2991   args.push_int(for_class);
2992   args.push_oop(filter_classes);
2993   Symbol* signature = vmSymbols::encodeAnnotations_signature();
2994   JavaCalls::call_static(&result,
2995                          vm_support,
2996                          vmSymbols::encodeAnnotations_name(),
2997                          signature,
2998                          &args,
2999                          CHECK_NULL);
3000 
3001   oop res = result.get_oop();
3002   if (JVMCIENV->is_hotspot()) {
3003     return (jbyteArray) JNIHandles::make_local(THREAD, res);
3004   }
3005 
3006   typeArrayOop ba = typeArrayOop(res);
3007   int ba_len = ba->length();
3008   jbyte* ba_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jbyte, ba_len);
3009   if (ba_buf == nullptr) {
3010     JVMCI_THROW_MSG_NULL(InternalError,
3011               err_msg("could not allocate %d bytes", ba_len));
3012 
3013   }
3014   memcpy(ba_buf, ba->byte_at_addr(0), ba_len);
3015   JVMCIPrimitiveArray ba_dest = JVMCIENV->new_byteArray(ba_len, JVMCI_CHECK_NULL);
3016   JVMCIENV->copy_bytes_from(ba_buf, ba_dest, 0, ba_len);
3017   return JVMCIENV->get_jbyteArray(ba_dest);
3018 }
3019 
3020 C2V_VMENTRY_NULL(jbyteArray, getEncodedClassAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass),
3021                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3022   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3023   InstanceKlass* holder = InstanceKlass::cast(UNPACK_PAIR(Klass, klass));
3024   return get_encoded_annotation_data(holder, holder->class_annotations(), true, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3025 C2V_END
3026 
3027 C2V_VMENTRY_NULL(jbyteArray, getEncodedExecutableAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3028                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3029   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3030   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3031   return get_encoded_annotation_data(method->method_holder(), method->annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3032 C2V_END
3033 
3034 C2V_VMENTRY_NULL(jbyteArray, getEncodedFieldAnnotationData, (JNIEnv* env, jobject, ARGUMENT_PAIR(klass), jint index,
3035                  jobject filter, jint filter_length, jlong filter_klass_pointers))
3036   CompilerThreadCanCallJava canCallJava(thread, true); // Requires Java support
3037   InstanceKlass* holder = check_field(InstanceKlass::cast(UNPACK_PAIR(Klass, klass)), index, JVMCIENV);
3038   fieldDescriptor fd(holder, index);
3039   return get_encoded_annotation_data(holder, fd.annotations(), false, filter_length, filter_klass_pointers, THREAD, JVMCIENV);
3040 C2V_END
3041 
3042 C2V_VMENTRY_NULL(jobjectArray, getFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address, jobjectArray current))
3043   FailedSpeculation* head = *((FailedSpeculation**)(address) failed_speculations_address);
3044   int result_length = 0;
3045   for (FailedSpeculation* fs = head; fs != nullptr; fs = fs->next()) {
3046     result_length++;
3047   }
3048   int current_length = 0;
3049   JVMCIObjectArray current_array = nullptr;
3050   if (current != nullptr) {
3051     current_array = JVMCIENV->wrap(current);
3052     current_length = JVMCIENV->get_length(current_array);
3053     if (current_length == result_length) {
3054       // No new failures
3055       return current;
3056     }
3057   }
3058   JVMCIObjectArray result = JVMCIENV->new_byte_array_array(result_length, JVMCI_CHECK_NULL);
3059   int result_index = 0;
3060   for (FailedSpeculation* fs = head; result_index < result_length; fs = fs->next()) {
3061     assert(fs != nullptr, "npe");
3062     JVMCIPrimitiveArray entry;
3063     if (result_index < current_length) {
3064       entry = (JVMCIPrimitiveArray) JVMCIENV->get_object_at(current_array, result_index);
3065     } else {
3066       entry = JVMCIENV->new_byteArray(fs->data_len(), JVMCI_CHECK_NULL);
3067       JVMCIENV->copy_bytes_from((jbyte*) fs->data(), entry, 0, fs->data_len());
3068     }
3069     JVMCIENV->put_object_at(result, result_index++, entry);
3070   }
3071   return JVMCIENV->get_jobjectArray(result);
3072 C2V_END
3073 
3074 C2V_VMENTRY_0(jlong, getFailedSpeculationsAddress, (JNIEnv* env, jobject, ARGUMENT_PAIR(method)))
3075   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3076   MethodData* method_data = get_profiling_method_data(method, CHECK_0);
3077   return (jlong) method_data->get_failed_speculations_address();
3078 C2V_END
3079 
3080 C2V_VMENTRY(void, releaseFailedSpeculations, (JNIEnv* env, jobject, jlong failed_speculations_address))
3081   FailedSpeculation::free_failed_speculations((FailedSpeculation**)(address) failed_speculations_address);
3082 C2V_END
3083 
3084 C2V_VMENTRY_0(jboolean, addFailedSpeculation, (JNIEnv* env, jobject, jlong failed_speculations_address, jbyteArray speculation_obj))
3085   JVMCIPrimitiveArray speculation_handle = JVMCIENV->wrap(speculation_obj);
3086   int speculation_len = JVMCIENV->get_length(speculation_handle);
3087   char* speculation = NEW_RESOURCE_ARRAY(char, speculation_len);
3088   JVMCIENV->copy_bytes_to(speculation_handle, (jbyte*) speculation, 0, speculation_len);
3089   return FailedSpeculation::add_failed_speculation(nullptr, (FailedSpeculation**)(address) failed_speculations_address, (address) speculation, speculation_len);
3090 C2V_END
3091 
3092 C2V_VMENTRY(void, callSystemExit, (JNIEnv* env, jobject, jint status))
3093   if (!JVMCIENV->is_hotspot()) {
3094     // It's generally not safe to call Java code before the module system is initialized
3095     if (!Universe::is_module_initialized()) {
3096       JVMCI_event_1("callSystemExit(%d) before Universe::is_module_initialized() -> direct VM exit", status);
3097       vm_exit_during_initialization();
3098     }
3099   }
3100   CompilerThreadCanCallJava canCallJava(thread, true);
3101   JavaValue result(T_VOID);
3102   JavaCallArguments jargs(1);
3103   jargs.push_int(status);
3104   JavaCalls::call_static(&result,
3105                        vmClasses::System_klass(),
3106                        vmSymbols::exit_method_name(),
3107                        vmSymbols::int_void_signature(),
3108                        &jargs,
3109                        CHECK);
3110 C2V_END
3111 
3112 C2V_VMENTRY_0(jlong, ticksNow, (JNIEnv* env, jobject))
3113   return CompilerEvent::ticksNow();
3114 C2V_END
3115 
3116 C2V_VMENTRY_0(jint, registerCompilerPhase, (JNIEnv* env, jobject, jstring jphase_name))
3117 #if INCLUDE_JFR
3118   JVMCIObject phase_name = JVMCIENV->wrap(jphase_name);
3119   const char *name = JVMCIENV->as_utf8_string(phase_name);
3120   return CompilerEvent::PhaseEvent::get_phase_id(name, true, true, true);
3121 #else
3122   return -1;
3123 #endif // !INCLUDE_JFR
3124 C2V_END
3125 
3126 C2V_VMENTRY(void, notifyCompilerPhaseEvent, (JNIEnv* env, jobject, jlong startTime, jint phase, jint compileId, jint level))
3127   EventCompilerPhase event(UNTIMED);
3128   if (event.should_commit()) {
3129     CompilerEvent::PhaseEvent::post(event, startTime, phase, compileId, level);
3130   }
3131 C2V_END
3132 
3133 C2V_VMENTRY(void, notifyCompilerInliningEvent, (JNIEnv* env, jobject, jint compileId, ARGUMENT_PAIR(caller), ARGUMENT_PAIR(callee), jboolean succeeded, jstring jmessage, jint bci))
3134   EventCompilerInlining event;
3135   if (event.should_commit()) {
3136     Method* caller = UNPACK_PAIR(Method, caller);
3137     Method* callee = UNPACK_PAIR(Method, callee);
3138     JVMCIObject message = JVMCIENV->wrap(jmessage);
3139     CompilerEvent::InlineEvent::post(event, compileId, caller, callee, succeeded, JVMCIENV->as_utf8_string(message), bci);
3140   }
3141 C2V_END
3142 
3143 C2V_VMENTRY(void, setThreadLocalObject, (JNIEnv* env, jobject, jint id, jobject value))
3144   requireInHotSpot("setThreadLocalObject", JVMCI_CHECK);
3145   if (id == 0) {
3146     thread->set_jvmci_reserved_oop0(JNIHandles::resolve(value));
3147     return;
3148   }
3149   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3150             err_msg("%d is not a valid thread local id", id));
3151 C2V_END
3152 
3153 C2V_VMENTRY_NULL(jobject, getThreadLocalObject, (JNIEnv* env, jobject, jint id))
3154   requireInHotSpot("getThreadLocalObject", JVMCI_CHECK_NULL);
3155   if (id == 0) {
3156     return JNIHandles::make_local(thread->get_jvmci_reserved_oop0());
3157   }
3158   THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
3159                  err_msg("%d is not a valid thread local id", id));
3160 C2V_END
3161 
3162 C2V_VMENTRY(void, setThreadLocalLong, (JNIEnv* env, jobject, jint id, jlong value))
3163   requireInHotSpot("setThreadLocalLong", JVMCI_CHECK);
3164   if (id == 0) {
3165     thread->set_jvmci_reserved0(value);
3166   } else if (id == 1) {
3167     thread->set_jvmci_reserved1(value);
3168   } else {
3169     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
3170               err_msg("%d is not a valid thread local id", id));
3171   }
3172 C2V_END
3173 
3174 C2V_VMENTRY_0(jlong, getThreadLocalLong, (JNIEnv* env, jobject, jint id))
3175   requireInHotSpot("getThreadLocalLong", JVMCI_CHECK_0);
3176   if (id == 0) {
3177     return thread->get_jvmci_reserved0();
3178   } else if (id == 1) {
3179     return thread->get_jvmci_reserved1();
3180   } else {
3181     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
3182                 err_msg("%d is not a valid thread local id", id));
3183   }
3184 C2V_END
3185 
3186 C2V_VMENTRY(void, getOopMapAt, (JNIEnv* env, jobject, ARGUMENT_PAIR(method),
3187                  jint bci, jlongArray oop_map_handle))
3188   methodHandle method(THREAD, UNPACK_PAIR(Method, method));
3189   if (bci < 0 || bci >= method->code_size()) {
3190     JVMCI_THROW_MSG(IllegalArgumentException,
3191                 err_msg("bci %d is out of bounds [0 .. %d)", bci, method->code_size()));
3192   }
3193   InterpreterOopMap mask;
3194   OopMapCache::compute_one_oop_map(method, bci, &mask);
3195   if (!mask.has_valid_mask()) {
3196     JVMCI_THROW_MSG(IllegalArgumentException, err_msg("bci %d is not valid", bci));
3197   }
3198   if (mask.number_of_entries() == 0) {
3199     return;
3200   }
3201 
3202   int nslots = method->max_locals() + method->max_stack();
3203   int nwords = ((nslots - 1) / 64) + 1;
3204   JVMCIPrimitiveArray oop_map = JVMCIENV->wrap(oop_map_handle);
3205   int oop_map_len = JVMCIENV->get_length(oop_map);
3206   if (nwords > oop_map_len) {
3207     JVMCI_THROW_MSG(IllegalArgumentException,
3208                 err_msg("oop map too short: %d > %d", nwords, oop_map_len));
3209   }
3210 
3211   jlong* oop_map_buf = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, jlong, nwords);
3212   if (oop_map_buf == nullptr) {
3213     JVMCI_THROW_MSG(InternalError, err_msg("could not allocate %d longs", nwords));
3214   }
3215   for (int i = 0; i < nwords; i++) {
3216     oop_map_buf[i] = 0L;
3217   }
3218 
3219   BitMapView oop_map_view = BitMapView((BitMap::bm_word_t*) oop_map_buf, nwords * BitsPerLong);
3220   for (int i = 0; i < nslots; i++) {
3221     if (mask.is_oop(i)) {
3222       oop_map_view.set_bit(i);
3223     }
3224   }
3225   JVMCIENV->copy_longs_from((jlong*)oop_map_buf, oop_map, 0, nwords);
3226 C2V_END
3227 
3228 #define CC (char*)  /*cast a literal from (const char*)*/
3229 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
3230 
3231 #define STRING                  "Ljava/lang/String;"
3232 #define OBJECT                  "Ljava/lang/Object;"
3233 #define CLASS                   "Ljava/lang/Class;"
3234 #define OBJECTCONSTANT          "Ljdk/vm/ci/hotspot/HotSpotObjectConstantImpl;"
3235 #define EXECUTABLE              "Ljava/lang/reflect/Executable;"
3236 #define STACK_TRACE_ELEMENT     "Ljava/lang/StackTraceElement;"
3237 #define INSTALLED_CODE          "Ljdk/vm/ci/code/InstalledCode;"
3238 #define BYTECODE_FRAME          "Ljdk/vm/ci/code/BytecodeFrame;"
3239 #define JAVACONSTANT            "Ljdk/vm/ci/meta/JavaConstant;"
3240 #define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
3241 #define RESOLVED_METHOD         "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
3242 #define FIELDINFO               "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl$FieldInfo;"
3243 #define HS_RESOLVED_TYPE        "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaType;"
3244 #define HS_INSTALLED_CODE       "Ljdk/vm/ci/hotspot/HotSpotInstalledCode;"
3245 #define HS_NMETHOD              "Ljdk/vm/ci/hotspot/HotSpotNmethod;"
3246 #define HS_COMPILED_CODE        "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
3247 #define HS_CONFIG               "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
3248 #define HS_STACK_FRAME_REF      "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
3249 #define HS_SPECULATION_LOG      "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
3250 #define REFLECTION_EXECUTABLE   "Ljava/lang/reflect/Executable;"
3251 #define REFLECTION_FIELD        "Ljava/lang/reflect/Field;"
3252 
3253 // Types wrapping VM pointers. The ...2 macro is for a pair: (wrapper, pointer)
3254 #define HS_METHOD               "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
3255 #define HS_METHOD2              "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;J"
3256 #define HS_KLASS                "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
3257 #define HS_KLASS2               "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;J"
3258 #define HS_CONSTANT_POOL        "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
3259 #define HS_CONSTANT_POOL2       "Ljdk/vm/ci/hotspot/HotSpotConstantPool;J"
3260 
3261 JNINativeMethod CompilerToVM::methods[] = {
3262   {CC "getBytecode",                                  CC "(" HS_METHOD2 ")[B",                                                              FN_PTR(getBytecode)},
3263   {CC "getExceptionTableStart",                       CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getExceptionTableStart)},
3264   {CC "getExceptionTableLength",                      CC "(" HS_METHOD2 ")I",                                                               FN_PTR(getExceptionTableLength)},
3265   {CC "findUniqueConcreteMethod",                     CC "(" HS_KLASS2 HS_METHOD2 ")" HS_METHOD,                                            FN_PTR(findUniqueConcreteMethod)},
3266   {CC "getImplementor",                               CC "(" HS_KLASS2 ")" HS_KLASS,                                                        FN_PTR(getImplementor)},
3267   {CC "getStackTraceElement",                         CC "(" HS_METHOD2 "I)" STACK_TRACE_ELEMENT,                                           FN_PTR(getStackTraceElement)},
3268   {CC "methodIsIgnoredBySecurityStackWalk",           CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(methodIsIgnoredBySecurityStackWalk)},
3269   {CC "setNotInlinableOrCompilable",                  CC "(" HS_METHOD2 ")V",                                                               FN_PTR(setNotInlinableOrCompilable)},
3270   {CC "isCompilable",                                 CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(isCompilable)},
3271   {CC "hasNeverInlineDirective",                      CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(hasNeverInlineDirective)},
3272   {CC "shouldInlineMethod",                           CC "(" HS_METHOD2 ")Z",                                                               FN_PTR(shouldInlineMethod)},
3273   {CC "lookupType",                                   CC "(" STRING HS_KLASS2 "IZ)" HS_RESOLVED_TYPE,                                       FN_PTR(lookupType)},
3274   {CC "lookupJClass",                                 CC "(J)" HS_RESOLVED_TYPE,                                                            FN_PTR(lookupJClass)},
3275   {CC "getJObjectValue",                              CC "(" OBJECTCONSTANT ")J",                                                           FN_PTR(getJObjectValue)},
3276   {CC "getArrayType",                                 CC "(C" HS_KLASS2 ")" HS_KLASS,                                                       FN_PTR(getArrayType)},
3277   {CC "lookupClass",                                  CC "(" CLASS ")" HS_RESOLVED_TYPE,                                                    FN_PTR(lookupClass)},
3278   {CC "lookupNameInPool",                             CC "(" HS_CONSTANT_POOL2 "II)" STRING,                                                FN_PTR(lookupNameInPool)},
3279   {CC "lookupNameAndTypeRefIndexInPool",              CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(lookupNameAndTypeRefIndexInPool)},
3280   {CC "lookupSignatureInPool",                        CC "(" HS_CONSTANT_POOL2 "II)" STRING,                                                FN_PTR(lookupSignatureInPool)},
3281   {CC "lookupKlassRefIndexInPool",                    CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(lookupKlassRefIndexInPool)},
3282   {CC "lookupKlassInPool",                            CC "(" HS_CONSTANT_POOL2 "I)Ljava/lang/Object;",                                      FN_PTR(lookupKlassInPool)},
3283   {CC "lookupAppendixInPool",                         CC "(" HS_CONSTANT_POOL2 "II)" OBJECTCONSTANT,                                        FN_PTR(lookupAppendixInPool)},
3284   {CC "lookupMethodInPool",                           CC "(" HS_CONSTANT_POOL2 "IB" HS_METHOD2 ")" HS_METHOD,                               FN_PTR(lookupMethodInPool)},
3285   {CC "lookupConstantInPool",                         CC "(" HS_CONSTANT_POOL2 "IZ)" JAVACONSTANT,                                          FN_PTR(lookupConstantInPool)},
3286   {CC "resolveBootstrapMethod",                       CC "(" HS_CONSTANT_POOL2 "I)[" OBJECT,                                                FN_PTR(resolveBootstrapMethod)},
3287   {CC "bootstrapArgumentIndexAt",                     CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(bootstrapArgumentIndexAt)},
3288   {CC "getUncachedStringInPool",                      CC "(" HS_CONSTANT_POOL2 "I)" JAVACONSTANT,                                           FN_PTR(getUncachedStringInPool)},
3289   {CC "resolveTypeInPool",                            CC "(" HS_CONSTANT_POOL2 "I)" HS_KLASS,                                               FN_PTR(resolveTypeInPool)},
3290   {CC "resolveFieldInPool",                           CC "(" HS_CONSTANT_POOL2 "I" HS_METHOD2 "B[I)" HS_KLASS,                              FN_PTR(resolveFieldInPool)},
3291   {CC "decodeFieldIndexToCPIndex",                    CC "(" HS_CONSTANT_POOL2 "I)I",                                                       FN_PTR(decodeFieldIndexToCPIndex)},
3292   {CC "decodeMethodIndexToCPIndex",                   CC "(" HS_CONSTANT_POOL2 "I)I",                                                       FN_PTR(decodeMethodIndexToCPIndex)},
3293   {CC "decodeIndyIndexToCPIndex",                     CC "(" HS_CONSTANT_POOL2 "IZ)I",                                                      FN_PTR(decodeIndyIndexToCPIndex)},
3294   {CC "resolveInvokeHandleInPool",                    CC "(" HS_CONSTANT_POOL2 "I)V",                                                       FN_PTR(resolveInvokeHandleInPool)},
3295   {CC "isResolvedInvokeHandleInPool",                 CC "(" HS_CONSTANT_POOL2 "II)I",                                                      FN_PTR(isResolvedInvokeHandleInPool)},
3296   {CC "resolveMethod",                                CC "(" HS_KLASS2 HS_METHOD2 HS_KLASS2 ")" HS_METHOD,                                  FN_PTR(resolveMethod)},
3297   {CC "getSignaturePolymorphicHolders",               CC "()[" STRING,                                                                      FN_PTR(getSignaturePolymorphicHolders)},
3298   {CC "getVtableIndexForInterfaceMethod",             CC "(" HS_KLASS2 HS_METHOD2 ")I",                                                     FN_PTR(getVtableIndexForInterfaceMethod)},
3299   {CC "getClassInitializer",                          CC "(" HS_KLASS2 ")" HS_METHOD,                                                       FN_PTR(getClassInitializer)},
3300   {CC "hasFinalizableSubclass",                       CC "(" HS_KLASS2 ")Z",                                                                FN_PTR(hasFinalizableSubclass)},
3301   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
3302   {CC "asResolvedJavaMethod",                         CC "(" EXECUTABLE ")" HS_METHOD,                                                      FN_PTR(asResolvedJavaMethod)},
3303   {CC "getResolvedJavaMethod",                        CC "(" OBJECTCONSTANT "J)" HS_METHOD,                                                 FN_PTR(getResolvedJavaMethod)},
3304   {CC "getConstantPool",                              CC "(" OBJECT "JZ)" HS_CONSTANT_POOL,                                                 FN_PTR(getConstantPool)},
3305   {CC "getResolvedJavaType0",                         CC "(Ljava/lang/Object;JZ)" HS_KLASS,                                                 FN_PTR(getResolvedJavaType0)},
3306   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
3307   {CC "installCode0",                                 CC "(JJZ" HS_COMPILED_CODE "[" OBJECT INSTALLED_CODE "J[B)I",                         FN_PTR(installCode0)},
3308   {CC "getInstallCodeFlags",                          CC "()I",                                                                             FN_PTR(getInstallCodeFlags)},
3309   {CC "resetCompilationStatistics",                   CC "()V",                                                                             FN_PTR(resetCompilationStatistics)},
3310   {CC "disassembleCodeBlob",                          CC "(" INSTALLED_CODE ")" STRING,                                                     FN_PTR(disassembleCodeBlob)},
3311   {CC "executeHotSpotNmethod",                        CC "([" OBJECT HS_NMETHOD ")" OBJECT,                                                 FN_PTR(executeHotSpotNmethod)},
3312   {CC "getLineNumberTable",                           CC "(" HS_METHOD2 ")[J",                                                              FN_PTR(getLineNumberTable)},
3313   {CC "getLocalVariableTableStart",                   CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getLocalVariableTableStart)},
3314   {CC "getLocalVariableTableLength",                  CC "(" HS_METHOD2 ")I",                                                               FN_PTR(getLocalVariableTableLength)},
3315   {CC "reprofile",                                    CC "(" HS_METHOD2 ")V",                                                               FN_PTR(reprofile)},
3316   {CC "invalidateHotSpotNmethod",                     CC "(" HS_NMETHOD "Z)V",                                                              FN_PTR(invalidateHotSpotNmethod)},
3317   {CC "collectCounters",                              CC "()[J",                                                                            FN_PTR(collectCounters)},
3318   {CC "getCountersSize",                              CC "()I",                                                                             FN_PTR(getCountersSize)},
3319   {CC "setCountersSize",                              CC "(I)Z",                                                                            FN_PTR(setCountersSize)},
3320   {CC "allocateCompileId",                            CC "(" HS_METHOD2 "I)I",                                                              FN_PTR(allocateCompileId)},
3321   {CC "isMature",                                     CC "(J)Z",                                                                            FN_PTR(isMature)},
3322   {CC "hasCompiledCodeForOSR",                        CC "(" HS_METHOD2 "II)Z",                                                             FN_PTR(hasCompiledCodeForOSR)},
3323   {CC "getSymbol",                                    CC "(J)" STRING,                                                                      FN_PTR(getSymbol)},
3324   {CC "getSignatureName",                             CC "(J)" STRING,                                                                      FN_PTR(getSignatureName)},
3325   {CC "iterateFrames",                                CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT,   FN_PTR(iterateFrames)},
3326   {CC "materializeVirtualObjects",                    CC "(" HS_STACK_FRAME_REF "Z)V",                                                      FN_PTR(materializeVirtualObjects)},
3327   {CC "shouldDebugNonSafepoints",                     CC "()Z",                                                                             FN_PTR(shouldDebugNonSafepoints)},
3328   {CC "writeDebugOutput",                             CC "(JIZ)V",                                                                          FN_PTR(writeDebugOutput)},
3329   {CC "flushDebugOutput",                             CC "()V",                                                                             FN_PTR(flushDebugOutput)},
3330   {CC "methodDataProfileDataSize",                    CC "(JI)I",                                                                           FN_PTR(methodDataProfileDataSize)},
3331   {CC "methodDataExceptionSeen",                      CC "(JI)I",                                                                           FN_PTR(methodDataExceptionSeen)},
3332   {CC "interpreterFrameSize",                         CC "(" BYTECODE_FRAME ")I",                                                           FN_PTR(interpreterFrameSize)},
3333   {CC "compileToBytecode",                            CC "(" OBJECTCONSTANT ")V",                                                           FN_PTR(compileToBytecode)},
3334   {CC "getFlagValue",                                 CC "(" STRING ")" OBJECT,                                                             FN_PTR(getFlagValue)},
3335   {CC "getInterfaces",                                CC "(" HS_KLASS2 ")[" HS_KLASS,                                                       FN_PTR(getInterfaces)},
3336   {CC "getComponentType",                             CC "(" HS_KLASS2 ")" HS_RESOLVED_TYPE,                                                FN_PTR(getComponentType)},
3337   {CC "ensureInitialized",                            CC "(" HS_KLASS2 ")V",                                                                FN_PTR(ensureInitialized)},
3338   {CC "ensureLinked",                                 CC "(" HS_KLASS2 ")V",                                                                FN_PTR(ensureLinked)},
3339   {CC "getIdentityHashCode",                          CC "(" OBJECTCONSTANT ")I",                                                           FN_PTR(getIdentityHashCode)},
3340   {CC "isInternedString",                             CC "(" OBJECTCONSTANT ")Z",                                                           FN_PTR(isInternedString)},
3341   {CC "unboxPrimitive",                               CC "(" OBJECTCONSTANT ")" OBJECT,                                                     FN_PTR(unboxPrimitive)},
3342   {CC "boxPrimitive",                                 CC "(" OBJECT ")" OBJECTCONSTANT,                                                     FN_PTR(boxPrimitive)},
3343   {CC "getDeclaredConstructors",                      CC "(" HS_KLASS2 ")[" RESOLVED_METHOD,                                                FN_PTR(getDeclaredConstructors)},
3344   {CC "getDeclaredMethods",                           CC "(" HS_KLASS2 ")[" RESOLVED_METHOD,                                                FN_PTR(getDeclaredMethods)},
3345   {CC "getDeclaredFieldsInfo",                        CC "(" HS_KLASS2 ")[" FIELDINFO,                                                      FN_PTR(getDeclaredFieldsInfo)},
3346   {CC "readStaticFieldValue",                         CC "(" HS_KLASS2 "JC)" JAVACONSTANT,                                                  FN_PTR(readStaticFieldValue)},
3347   {CC "readFieldValue",                               CC "(" OBJECTCONSTANT HS_KLASS2 "JC)" JAVACONSTANT,                                   FN_PTR(readFieldValue)},
3348   {CC "isInstance",                                   CC "(" HS_KLASS2 OBJECTCONSTANT ")Z",                                                 FN_PTR(isInstance)},
3349   {CC "isAssignableFrom",                             CC "(" HS_KLASS2 HS_KLASS2 ")Z",                                                      FN_PTR(isAssignableFrom)},
3350   {CC "isTrustedForIntrinsics",                       CC "(" HS_KLASS2 ")Z",                                                                FN_PTR(isTrustedForIntrinsics)},
3351   {CC "asJavaType",                                   CC "(" OBJECTCONSTANT ")" HS_RESOLVED_TYPE,                                           FN_PTR(asJavaType)},
3352   {CC "asString",                                     CC "(" OBJECTCONSTANT ")" STRING,                                                     FN_PTR(asString)},
3353   {CC "equals",                                       CC "(" OBJECTCONSTANT "J" OBJECTCONSTANT "J)Z",                                       FN_PTR(equals)},
3354   {CC "getJavaMirror",                                CC "(" HS_KLASS2 ")" OBJECTCONSTANT,                                                  FN_PTR(getJavaMirror)},
3355   {CC "getArrayLength",                               CC "(" OBJECTCONSTANT ")I",                                                           FN_PTR(getArrayLength)},
3356   {CC "readArrayElement",                             CC "(" OBJECTCONSTANT "I)Ljava/lang/Object;",                                         FN_PTR(readArrayElement)},
3357   {CC "arrayBaseOffset",                              CC "(C)I",                                                                            FN_PTR(arrayBaseOffset)},
3358   {CC "arrayIndexScale",                              CC "(C)I",                                                                            FN_PTR(arrayIndexScale)},
3359   {CC "clearOopHandle",                               CC "(J)V",                                                                            FN_PTR(clearOopHandle)},
3360   {CC "releaseClearedOopHandles",                     CC "()V",                                                                             FN_PTR(releaseClearedOopHandles)},
3361   {CC "registerNativeMethods",                        CC "(" CLASS ")[J",                                                                   FN_PTR(registerNativeMethods)},
3362   {CC "isCurrentThreadAttached",                      CC "()Z",                                                                             FN_PTR(isCurrentThreadAttached)},
3363   {CC "getCurrentJavaThread",                         CC "()J",                                                                             FN_PTR(getCurrentJavaThread)},
3364   {CC "attachCurrentThread",                          CC "([BZ[J)Z",                                                                        FN_PTR(attachCurrentThread)},
3365   {CC "detachCurrentThread",                          CC "(Z)Z",                                                                            FN_PTR(detachCurrentThread)},
3366   {CC "translate",                                    CC "(" OBJECT "Z)J",                                                                  FN_PTR(translate)},
3367   {CC "unhand",                                       CC "(J)" OBJECT,                                                                      FN_PTR(unhand)},
3368   {CC "updateHotSpotNmethod",                         CC "(" HS_NMETHOD ")V",                                                               FN_PTR(updateHotSpotNmethod)},
3369   {CC "getCode",                                      CC "(" HS_INSTALLED_CODE ")[B",                                                       FN_PTR(getCode)},
3370   {CC "asReflectionExecutable",                       CC "(" HS_METHOD2 ")" REFLECTION_EXECUTABLE,                                          FN_PTR(asReflectionExecutable)},
3371   {CC "asReflectionField",                            CC "(" HS_KLASS2 "I)" REFLECTION_FIELD,                                               FN_PTR(asReflectionField)},
3372   {CC "getEncodedClassAnnotationData",                CC "(" HS_KLASS2 OBJECT "IJ)[B",                                                      FN_PTR(getEncodedClassAnnotationData)},
3373   {CC "getEncodedExecutableAnnotationData",           CC "(" HS_METHOD2 OBJECT "IJ)[B",                                                     FN_PTR(getEncodedExecutableAnnotationData)},
3374   {CC "getEncodedFieldAnnotationData",                CC "(" HS_KLASS2 "I" OBJECT "IJ)[B",                                                  FN_PTR(getEncodedFieldAnnotationData)},
3375   {CC "getFailedSpeculations",                        CC "(J[[B)[[B",                                                                       FN_PTR(getFailedSpeculations)},
3376   {CC "getFailedSpeculationsAddress",                 CC "(" HS_METHOD2 ")J",                                                               FN_PTR(getFailedSpeculationsAddress)},
3377   {CC "releaseFailedSpeculations",                    CC "(J)V",                                                                            FN_PTR(releaseFailedSpeculations)},
3378   {CC "addFailedSpeculation",                         CC "(J[B)Z",                                                                          FN_PTR(addFailedSpeculation)},
3379   {CC "callSystemExit",                               CC "(I)V",                                                                            FN_PTR(callSystemExit)},
3380   {CC "ticksNow",                                     CC "()J",                                                                             FN_PTR(ticksNow)},
3381   {CC "getThreadLocalObject",                         CC "(I)" OBJECT,                                                                      FN_PTR(getThreadLocalObject)},
3382   {CC "setThreadLocalObject",                         CC "(I" OBJECT ")V",                                                                  FN_PTR(setThreadLocalObject)},
3383   {CC "getThreadLocalLong",                           CC "(I)J",                                                                            FN_PTR(getThreadLocalLong)},
3384   {CC "setThreadLocalLong",                           CC "(IJ)V",                                                                           FN_PTR(setThreadLocalLong)},
3385   {CC "registerCompilerPhase",                        CC "(" STRING ")I",                                                                   FN_PTR(registerCompilerPhase)},
3386   {CC "notifyCompilerPhaseEvent",                     CC "(JIII)V",                                                                         FN_PTR(notifyCompilerPhaseEvent)},
3387   {CC "notifyCompilerInliningEvent",                  CC "(I" HS_METHOD2 HS_METHOD2 "ZLjava/lang/String;I)V",                               FN_PTR(notifyCompilerInliningEvent)},
3388   {CC "getOopMapAt",                                  CC "(" HS_METHOD2 "I[J)V",                                                            FN_PTR(getOopMapAt)},
3389 };
3390 
3391 int CompilerToVM::methods_count() {
3392   return sizeof(methods) / sizeof(JNINativeMethod);
3393 }