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