1 /*
   2  * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "ci/ciUtilities.inline.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/scopeDesc.hpp"
  28 #include "interpreter/linkResolver.hpp"
  29 #include "memory/oopFactory.hpp"
  30 #include "oops/cpCache.inline.hpp"
  31 #include "oops/generateOopMap.hpp"
  32 #include "oops/method.inline.hpp"
  33 #include "oops/objArrayOop.inline.hpp"
  34 #include "oops/typeArrayOop.inline.hpp"
  35 #include "compiler/compileBroker.hpp"
  36 #include "compiler/disassembler.hpp"
  37 #include "jvmci/jvmciCompilerToVM.hpp"
  38 #include "jvmci/jvmciCodeInstaller.hpp"
  39 #include "jvmci/jvmciRuntime.hpp"
  40 #include "runtime/fieldDescriptor.inline.hpp"
  41 #include "runtime/flags/jvmFlag.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/handles.inline.hpp"
  44 #include "runtime/interfaceSupport.inline.hpp"
  45 #include "runtime/jniHandles.inline.hpp"
  46 #include "runtime/timerTrace.hpp"
  47 #include "runtime/vframe_hp.hpp"
  48 
  49 JVMCIKlassHandle::JVMCIKlassHandle(Thread* thread, Klass* klass) {
  50   _thread = thread;
  51   _klass = klass;
  52   if (klass != NULL) {
  53     _holder = Handle(_thread, klass->klass_holder());
  54   }
  55 }
  56 
  57 JVMCIKlassHandle& JVMCIKlassHandle::operator=(Klass* klass) {
  58   _klass = klass;
  59   if (klass != NULL) {
  60     _holder = Handle(_thread, klass->klass_holder());
  61   }
  62   return *this;
  63 }
  64 
  65 void JNIHandleMark::push_jni_handle_block() {
  66   JavaThread* thread = JavaThread::current();
  67   if (thread != NULL) {
  68     // Allocate a new block for JNI handles.
  69     // Inlined code from jni_PushLocalFrame()
  70     JNIHandleBlock* java_handles = ((JavaThread*)thread)->active_handles();
  71     JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread);
  72     assert(compile_handles != NULL && java_handles != NULL, "should not be NULL");
  73     compile_handles->set_pop_frame_link(java_handles);
  74     thread->set_active_handles(compile_handles);
  75   }
  76 }
  77 
  78 void JNIHandleMark::pop_jni_handle_block() {
  79   JavaThread* thread = JavaThread::current();
  80   if (thread != NULL) {
  81     // Release our JNI handle block
  82     JNIHandleBlock* compile_handles = thread->active_handles();
  83     JNIHandleBlock* java_handles = compile_handles->pop_frame_link();
  84     thread->set_active_handles(java_handles);
  85     compile_handles->set_pop_frame_link(NULL);
  86     JNIHandleBlock::release_block(compile_handles, thread); // may block
  87   }
  88 }
  89 
  90 // Entry to native method implementation that transitions current thread to '_thread_in_vm'.
  91 #define C2V_VMENTRY(result_type, name, signature) \
  92   JNIEXPORT result_type JNICALL c2v_ ## name signature { \
  93   TRACE_jvmci_1("CompilerToVM::" #name); \
  94   TRACE_CALL(result_type, jvmci_ ## name signature) \
  95   JVMCI_VM_ENTRY_MARK; \
  96 
  97 #define C2V_END }
  98 
  99 oop CompilerToVM::get_jvmci_method(const methodHandle& method, TRAPS) {
 100   if (method() != NULL) {
 101     JavaValue result(T_OBJECT);
 102     JavaCallArguments args;
 103     args.push_long((jlong) (address) method());
 104     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedJavaMethodImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::method_fromMetaspace_signature(), &args, CHECK_NULL);
 105 
 106     return (oop)result.get_jobject();
 107   }
 108   return NULL;
 109 }
 110 
 111 oop CompilerToVM::get_jvmci_type(JVMCIKlassHandle& klass, TRAPS) {
 112   if (!klass.is_null()) {
 113     JavaValue result(T_OBJECT);
 114     JavaCallArguments args;
 115     args.push_oop(Handle(THREAD, klass->java_mirror()));
 116     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedObjectTypeImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::klass_fromMetaspace_signature(), &args, CHECK_NULL);
 117 
 118     return (oop)result.get_jobject();
 119   }
 120   return NULL;
 121 }
 122 
 123 Handle JavaArgumentUnboxer::next_arg(BasicType expectedType) {
 124   assert(_index < _args->length(), "out of bounds");
 125   oop arg=((objArrayOop) (_args))->obj_at(_index++);
 126   assert(expectedType == T_OBJECT || java_lang_boxing_object::is_instance(arg, expectedType), "arg type mismatch");
 127   return Handle(Thread::current(), arg);
 128 }
 129 
 130 jobjectArray readConfiguration0(JNIEnv *env, TRAPS);
 131 
 132 C2V_VMENTRY(jobjectArray, readConfiguration, (JNIEnv *env))
 133    jobjectArray config = readConfiguration0(env, CHECK_NULL);
 134    return config;
 135 C2V_END
 136 
 137 C2V_VMENTRY(jobject, getFlagValue, (JNIEnv *, jobject c2vm, jobject name_handle))
 138 #define RETURN_BOXED_LONG(value) oop box; jvalue p; p.j = (jlong) (value); box = java_lang_boxing_object::create(T_LONG, &p, CHECK_NULL); return JNIHandles::make_local(THREAD, box);
 139 #define RETURN_BOXED_DOUBLE(value) oop box; jvalue p; p.d = (jdouble) (value); box = java_lang_boxing_object::create(T_DOUBLE, &p, CHECK_NULL); return JNIHandles::make_local(THREAD, box);
 140   Handle name(THREAD, JNIHandles::resolve(name_handle));
 141   if (name.is_null()) {
 142     THROW_0(vmSymbols::java_lang_NullPointerException());
 143   }
 144   ResourceMark rm;
 145   const char* cstring = java_lang_String::as_utf8_string(name());
 146   JVMFlag* flag = JVMFlag::find_flag(cstring, strlen(cstring), /* allow_locked */ true, /* return_flag */ true);
 147   if (flag == NULL) {
 148     return c2vm;
 149   }
 150   if (flag->is_bool()) {
 151     jvalue prim;
 152     prim.z = flag->get_bool();
 153     oop box = java_lang_boxing_object::create(T_BOOLEAN, &prim, CHECK_NULL);
 154     return JNIHandles::make_local(THREAD, box);
 155   } else if (flag->is_ccstr()) {
 156     Handle value = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_NULL);
 157     return JNIHandles::make_local(THREAD, value());
 158   } else if (flag->is_intx()) {
 159     RETURN_BOXED_LONG(flag->get_intx());
 160   } else if (flag->is_int()) {
 161     RETURN_BOXED_LONG(flag->get_int());
 162   } else if (flag->is_uint()) {
 163     RETURN_BOXED_LONG(flag->get_uint());
 164   } else if (flag->is_uint64_t()) {
 165     RETURN_BOXED_LONG(flag->get_uint64_t());
 166   } else if (flag->is_size_t()) {
 167     RETURN_BOXED_LONG(flag->get_size_t());
 168   } else if (flag->is_uintx()) {
 169     RETURN_BOXED_LONG(flag->get_uintx());
 170   } else if (flag->is_double()) {
 171     RETURN_BOXED_DOUBLE(flag->get_double());
 172   } else {
 173     JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->_name, flag->_type);
 174   }
 175 #undef RETURN_BOXED_LONG
 176 #undef RETURN_BOXED_DOUBLE
 177 C2V_END
 178 
 179 C2V_VMENTRY(jbyteArray, getBytecode, (JNIEnv *, jobject, jobject jvmci_method))
 180   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 181   ResourceMark rm;
 182 
 183   int code_size = method->code_size();
 184   typeArrayOop reconstituted_code = oopFactory::new_byteArray(code_size, CHECK_NULL);
 185 
 186   guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
 187   // iterate over all bytecodes and replace non-Java bytecodes
 188 
 189   for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
 190     Bytecodes::Code code = s.code();
 191     Bytecodes::Code raw_code = s.raw_code();
 192     int bci = s.bci();
 193     int len = s.instruction_size();
 194 
 195     // Restore original byte code.
 196     reconstituted_code->byte_at_put(bci, (jbyte) (s.is_wide()? Bytecodes::_wide : code));
 197     if (len > 1) {
 198       memcpy(reconstituted_code->byte_at_addr(bci + 1), s.bcp()+1, len-1);
 199     }
 200 
 201     if (len > 1) {
 202       // Restore the big-endian constant pool indexes.
 203       // Cf. Rewriter::scan_method
 204       switch (code) {
 205         case Bytecodes::_getstatic:
 206         case Bytecodes::_putstatic:
 207         case Bytecodes::_getfield:
 208         case Bytecodes::_putfield:
 209         case Bytecodes::_invokevirtual:
 210         case Bytecodes::_invokespecial:
 211         case Bytecodes::_invokestatic:
 212         case Bytecodes::_invokeinterface:
 213         case Bytecodes::_invokehandle: {
 214           int cp_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 215           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 216           break;
 217         }
 218 
 219         case Bytecodes::_invokedynamic: {
 220           int cp_index = Bytes::get_native_u4((address) reconstituted_code->byte_at_addr(bci + 1));
 221           Bytes::put_Java_u4((address) reconstituted_code->byte_at_addr(bci + 1), (u4) cp_index);
 222           break;
 223         }
 224 
 225         default:
 226           break;
 227       }
 228 
 229       // Not all ldc byte code are rewritten.
 230       switch (raw_code) {
 231         case Bytecodes::_fast_aldc: {
 232           int cpc_index = reconstituted_code->byte_at(bci + 1) & 0xff;
 233           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 234           assert(cp_index < method->constants()->length(), "sanity check");
 235           reconstituted_code->byte_at_put(bci + 1, (jbyte) cp_index);
 236           break;
 237         }
 238 
 239         case Bytecodes::_fast_aldc_w: {
 240           int cpc_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 241           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 242           assert(cp_index < method->constants()->length(), "sanity check");
 243           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 244           break;
 245         }
 246 
 247         default:
 248           break;
 249       }
 250     }
 251   }
 252 
 253   return (jbyteArray) JNIHandles::make_local(THREAD, reconstituted_code);
 254 C2V_END
 255 
 256 C2V_VMENTRY(jint, getExceptionTableLength, (JNIEnv *, jobject, jobject jvmci_method))
 257   ResourceMark rm;
 258   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 259   return method->exception_table_length();
 260 C2V_END
 261 
 262 C2V_VMENTRY(jlong, getExceptionTableStart, (JNIEnv *, jobject, jobject jvmci_method))
 263   ResourceMark rm;
 264   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 265   if (method->exception_table_length() == 0) {
 266     return 0L;
 267   }
 268   return (jlong) (address) method->exception_table_start();
 269 C2V_END
 270 
 271 C2V_VMENTRY(jobject, asResolvedJavaMethod, (JNIEnv *, jobject, jobject executable_handle))
 272   oop executable = JNIHandles::resolve(executable_handle);
 273   oop mirror = NULL;
 274   int slot = 0;
 275 
 276   if (executable->klass() == SystemDictionary::reflect_Constructor_klass()) {
 277     mirror = java_lang_reflect_Constructor::clazz(executable);
 278     slot = java_lang_reflect_Constructor::slot(executable);
 279   } else {
 280     assert(executable->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
 281     mirror = java_lang_reflect_Method::clazz(executable);
 282     slot = java_lang_reflect_Method::slot(executable);
 283   }
 284   Klass* holder = java_lang_Class::as_Klass(mirror);
 285   methodHandle method = InstanceKlass::cast(holder)->method_with_idnum(slot);
 286   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 287   return JNIHandles::make_local(THREAD, result);
 288 }
 289 
 290 C2V_VMENTRY(jobject, getResolvedJavaMethod, (JNIEnv *, jobject, jobject base, jlong offset))
 291   methodHandle method;
 292   oop base_object = JNIHandles::resolve(base);
 293   if (base_object == NULL) {
 294     method = *((Method**)(offset));
 295   } else if (base_object->is_a(SystemDictionary::ResolvedMethodName_klass())) {
 296     method = (Method*) (intptr_t) base_object->long_field(offset);
 297   } else if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 298     method = *((Method**)(HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object) + offset));
 299   } else {
 300     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 301                 err_msg("Unexpected type: %s", base_object->klass()->external_name()));
 302   }
 303   assert (method.is_null() || method->is_method(), "invalid read");
 304   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 305   return JNIHandles::make_local(THREAD, result);
 306 }
 307 
 308 C2V_VMENTRY(jobject, getConstantPool, (JNIEnv *, jobject, jobject object_handle))
 309   constantPoolHandle cp;
 310   oop object = JNIHandles::resolve(object_handle);
 311   if (object == NULL) {
 312     THROW_0(vmSymbols::java_lang_NullPointerException());
 313   }
 314   if (object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 315     cp = CompilerToVM::asMethod(object)->constMethod()->constants();
 316   } else if (object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 317     cp = InstanceKlass::cast(CompilerToVM::asKlass(object))->constants();
 318   } else {
 319     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 320                 err_msg("Unexpected type: %s", object->klass()->external_name()));
 321   }
 322   assert(!cp.is_null(), "npe");
 323   JavaValue method_result(T_OBJECT);
 324   JavaCallArguments args;
 325   args.push_long((jlong) (address) cp());
 326   JavaCalls::call_static(&method_result, SystemDictionary::HotSpotConstantPool_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::constantPool_fromMetaspace_signature(), &args, CHECK_NULL);
 327   return JNIHandles::make_local(THREAD, (oop)method_result.get_jobject());
 328 }
 329 
 330 C2V_VMENTRY(jobject, getResolvedJavaType, (JNIEnv *, jobject, jobject base, jlong offset, jboolean compressed))
 331   JVMCIKlassHandle klass(THREAD);
 332   oop base_object = JNIHandles::resolve(base);
 333   jlong base_address = 0;
 334   if (base_object != NULL && offset == oopDesc::klass_offset_in_bytes()) {
 335     klass = base_object->klass();
 336   } else if (!compressed) {
 337     if (base_object != NULL) {
 338       if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 339         base_address = HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object);
 340       } else if (base_object->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 341         base_address = HotSpotConstantPool::metaspaceConstantPool(base_object);
 342       } else if (base_object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 343         base_address = (jlong) CompilerToVM::asKlass(base_object);
 344       } else if (base_object->is_a(SystemDictionary::Class_klass())) {
 345         base_address = (jlong) (address) base_object;
 346       } else {
 347         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 348                     err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", base_object->klass()->external_name(), offset, compressed ? "true" : "false"));
 349       }
 350     }
 351     klass = *((Klass**) (intptr_t) (base_address + offset));
 352   } else {
 353     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 354                 err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s",
 355                         base_object != NULL ? base_object->klass()->external_name() : "null",
 356                         offset, compressed ? "true" : "false"));
 357   }
 358   assert (klass == NULL || klass->is_klass(), "invalid read");
 359   oop result = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 360   return JNIHandles::make_local(THREAD, result);
 361 }
 362 
 363 C2V_VMENTRY(jobject, findUniqueConcreteMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 364   ResourceMark rm;
 365   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 366   Klass* holder = CompilerToVM::asKlass(jvmci_type);
 367   if (holder->is_interface()) {
 368     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", holder->external_name()));
 369   }
 370 
 371   methodHandle ucm;
 372   {
 373     MutexLocker locker(Compile_lock);
 374     ucm = Dependencies::find_unique_concrete_method(holder, method());
 375   }
 376   oop result = CompilerToVM::get_jvmci_method(ucm, CHECK_NULL);
 377   return JNIHandles::make_local(THREAD, result);
 378 C2V_END
 379 
 380 C2V_VMENTRY(jobject, getImplementor, (JNIEnv *, jobject, jobject jvmci_type))
 381   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 382   if (!klass->is_interface()) {
 383     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 384         err_msg("Expected interface type, got %s", klass->external_name()));
 385   }
 386   InstanceKlass* iklass = InstanceKlass::cast(klass);
 387   JVMCIKlassHandle handle(THREAD);
 388   {
 389     // Need Compile_lock around implementor()
 390     MutexLocker locker(Compile_lock);
 391     handle = iklass->implementor();
 392   }
 393   oop implementor = CompilerToVM::get_jvmci_type(handle, CHECK_NULL);
 394   return JNIHandles::make_local(THREAD, implementor);
 395 C2V_END
 396 
 397 C2V_VMENTRY(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv *, jobject, jobject jvmci_method))
 398   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 399   return method->is_ignored_by_security_stack_walk();
 400 C2V_END
 401 
 402 C2V_VMENTRY(jboolean, isCompilable,(JNIEnv *, jobject, jobject jvmci_method))
 403   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 404   constantPoolHandle cp = method->constMethod()->constants();
 405   assert(!cp.is_null(), "npe");
 406   // don't inline method when constant pool contains a CONSTANT_Dynamic
 407   return !method->is_not_compilable(CompLevel_full_optimization) && !cp->has_dynamic_constant();
 408 C2V_END
 409 
 410 C2V_VMENTRY(jboolean, hasNeverInlineDirective,(JNIEnv *, jobject, jobject jvmci_method))
 411   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 412   return !Inline || CompilerOracle::should_not_inline(method) || method->dont_inline();
 413 C2V_END
 414 
 415 C2V_VMENTRY(jboolean, shouldInlineMethod,(JNIEnv *, jobject, jobject jvmci_method))
 416   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 417   return CompilerOracle::should_inline(method) || method->force_inline();
 418 C2V_END
 419 
 420 C2V_VMENTRY(jobject, lookupType, (JNIEnv*, jobject, jstring jname, jclass accessing_class, jboolean resolve))
 421   ResourceMark rm;
 422   Handle name(THREAD, JNIHandles::resolve(jname));
 423   Symbol* class_name = java_lang_String::as_symbol(name(), CHECK_0);
 424   if (java_lang_String::length(name()) <= 1) {
 425     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Primitive type %s should be handled in Java code", class_name->as_C_string()));
 426   }
 427 
 428   JVMCIKlassHandle resolved_klass(THREAD);
 429   if (JNIHandles::resolve(accessing_class) == NULL) {
 430     THROW_0(vmSymbols::java_lang_NullPointerException());
 431   }
 432   Klass* accessing_klass = java_lang_Class::as_Klass(JNIHandles::resolve(accessing_class));
 433   Handle class_loader(THREAD, accessing_klass->class_loader());
 434   Handle protection_domain(THREAD, accessing_klass->protection_domain());
 435 
 436   if (resolve) {
 437     resolved_klass = SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK_0);
 438   } else {
 439     if ((class_name->char_at(0) == 'L' || class_name->char_at(0) == 'Q' ) &&
 440         class_name->ends_with(';')) {
 441       // This is a name from a signature.  Strip off the trimmings.
 442       // Call recursive to keep scope of strippedsym.
 443       TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1,
 444                                                           class_name->utf8_length()-2,
 445                                                           CHECK_0);
 446       resolved_klass = SystemDictionary::find(strippedsym, class_loader, protection_domain, CHECK_0);
 447     } else if (FieldType::is_array(class_name)) {
 448       FieldArrayInfo fd;
 449       // dimension and object_key in FieldArrayInfo are assigned as a side-effect
 450       // of this call
 451       BasicType t = FieldType::get_array_info(class_name, fd, CHECK_0);
 452       if (t == T_OBJECT) {
 453         TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1+fd.dimension(),
 454                                                             class_name->utf8_length()-2-fd.dimension(),
 455                                                             CHECK_0);
 456         // naked oop "k" is OK here -- we assign back into it
 457         resolved_klass = SystemDictionary::find(strippedsym,
 458                                                              class_loader,
 459                                                              protection_domain,
 460                                                              CHECK_0);
 461         if (!resolved_klass.is_null()) {
 462           resolved_klass = resolved_klass->array_klass(fd.dimension(), CHECK_0);
 463         }
 464       } else {
 465         resolved_klass = TypeArrayKlass::cast(Universe::typeArrayKlassObj(t))->array_klass(fd.dimension(), CHECK_0);
 466       }
 467     }
 468   }
 469   oop result = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 470   return JNIHandles::make_local(THREAD, result);
 471 C2V_END
 472 
 473 C2V_VMENTRY(jobject, resolveConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 474   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 475   oop result = cp->resolve_constant_at(index, CHECK_NULL);
 476   return JNIHandles::make_local(THREAD, result);
 477 C2V_END
 478 
 479 C2V_VMENTRY(jobject, resolvePossiblyCachedConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 480   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 481   oop result = cp->resolve_possibly_cached_constant_at(index, CHECK_NULL);
 482   return JNIHandles::make_local(THREAD, result);
 483 C2V_END
 484 
 485 C2V_VMENTRY(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 486   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 487   return cp->name_and_type_ref_index_at(index);
 488 C2V_END
 489 
 490 C2V_VMENTRY(jobject, lookupNameInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 491   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 492   Handle sym = java_lang_String::create_from_symbol(cp->name_ref_at(which), CHECK_NULL);
 493   return JNIHandles::make_local(THREAD, sym());
 494 C2V_END
 495 
 496 C2V_VMENTRY(jobject, lookupSignatureInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 497   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 498   Handle sym = java_lang_String::create_from_symbol(cp->signature_ref_at(which), CHECK_NULL);
 499   return JNIHandles::make_local(THREAD, sym());
 500 C2V_END
 501 
 502 C2V_VMENTRY(jint, lookupKlassRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 503   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 504   return cp->klass_ref_index_at(index);
 505 C2V_END
 506 
 507 C2V_VMENTRY(jobject, resolveTypeInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 508   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 509   Klass* klass = cp->klass_at(index, CHECK_NULL);
 510   JVMCIKlassHandle resolved_klass(THREAD, klass);
 511   if (resolved_klass->is_instance_klass()) {
 512     InstanceKlass::cast(resolved_klass())->link_class_or_fail(THREAD);
 513   }
 514   oop jvmci_type = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 515   return JNIHandles::make_local(THREAD, jvmci_type);
 516 C2V_END
 517 
 518 C2V_VMENTRY(jobject, lookupKlassInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 519   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 520   Klass* loading_klass = cp->pool_holder();
 521   bool is_accessible = false;
 522   JVMCIKlassHandle klass(THREAD, JVMCIEnv::get_klass_by_index(cp, index, is_accessible, loading_klass));
 523   Symbol* symbol = NULL;
 524   if (klass == NULL) {
 525     symbol = cp->klass_name_at(index);
 526   }
 527   oop result_oop;
 528   if (!klass.is_null()) {
 529     result_oop = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 530   } else {
 531     Handle result = java_lang_String::create_from_symbol(symbol, CHECK_NULL);
 532     result_oop = result();
 533   }
 534   return JNIHandles::make_local(THREAD, result_oop);
 535 C2V_END
 536 
 537 C2V_VMENTRY(jobject, lookupAppendixInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 538   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 539   oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, index);
 540   return JNIHandles::make_local(THREAD, appendix_oop);
 541 C2V_END
 542 
 543 C2V_VMENTRY(jobject, lookupMethodInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 544   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 545   InstanceKlass* pool_holder = cp->pool_holder();
 546   Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
 547   methodHandle method = JVMCIEnv::get_method_by_index(cp, index, bc, pool_holder);
 548   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 549   return JNIHandles::make_local(THREAD, result);
 550 C2V_END
 551 
 552 C2V_VMENTRY(jint, constantPoolRemapInstructionOperandFromCache, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 553   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 554   return cp->remap_instruction_operand_from_cache(index);
 555 C2V_END
 556 
 557 C2V_VMENTRY(jobject, resolveFieldInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jobject jvmci_method, jbyte opcode, jintArray info_handle))
 558   ResourceMark rm;
 559   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 560   Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
 561   fieldDescriptor fd;
 562   LinkInfo link_info(cp, index, (jvmci_method != NULL) ? CompilerToVM::asMethod(jvmci_method) : NULL, CHECK_0);
 563   LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_0);
 564   typeArrayOop info = (typeArrayOop) JNIHandles::resolve(info_handle);
 565   if (info == NULL || info->length() != 3) {
 566     JVMCI_ERROR_NULL("info must not be null and have a length of 3");
 567   }
 568   info->int_at_put(0, fd.access_flags().as_int());
 569   info->int_at_put(1, fd.offset());
 570   info->int_at_put(2, fd.index());
 571   JVMCIKlassHandle handle(THREAD, fd.field_holder());
 572   oop field_holder = CompilerToVM::get_jvmci_type(handle, CHECK_NULL);
 573   return JNIHandles::make_local(THREAD, field_holder);
 574 C2V_END
 575 
 576 C2V_VMENTRY(jint, getVtableIndexForInterfaceMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 577   ResourceMark rm;
 578   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 579   Method* method = CompilerToVM::asMethod(jvmci_method);
 580   if (klass->is_interface()) {
 581     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", klass->external_name()));
 582   }
 583   if (!method->method_holder()->is_interface()) {
 584     THROW_MSG_0(vmSymbols::java_lang_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()));
 585   }
 586   if (!InstanceKlass::cast(klass)->is_linked()) {
 587     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Class %s must be linked", klass->external_name()));
 588   }
 589   return LinkResolver::vtable_index_of_interface_method(klass, method);
 590 C2V_END
 591 
 592 C2V_VMENTRY(jobject, resolveMethod, (JNIEnv *, jobject, jobject receiver_jvmci_type, jobject jvmci_method, jobject caller_jvmci_type))
 593   Klass* recv_klass = CompilerToVM::asKlass(receiver_jvmci_type);
 594   Klass* caller_klass = CompilerToVM::asKlass(caller_jvmci_type);
 595   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 596 
 597   Klass* resolved     = method->method_holder();
 598   Symbol* h_name      = method->name();
 599   Symbol* h_signature = method->signature();
 600 
 601   if (MethodHandles::is_signature_polymorphic_method(method())) {
 602       // Signature polymorphic methods are already resolved, JVMCI just returns NULL in this case.
 603       return NULL;
 604   }
 605 
 606   if (method->name() == vmSymbols::clone_name() &&
 607       resolved == SystemDictionary::Object_klass() &&
 608       recv_klass->is_array_klass()) {
 609     // Resolution of the clone method on arrays always returns Object.clone even though that method
 610     // has protected access.  There's some trickery in the access checking to make this all work out
 611     // so it's necessary to pass in the array class as the resolved class to properly trigger this.
 612     // Otherwise it's impossible to resolve the array clone methods through JVMCI.  See
 613     // LinkResolver::check_method_accessability for the matching logic.
 614     resolved = recv_klass;
 615   }
 616 
 617   LinkInfo link_info(resolved, h_name, h_signature, caller_klass);
 618   methodHandle m;
 619   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 620   // the vtable has not been setup, and the LinkResolver will fail.
 621   if (recv_klass->is_array_klass() ||
 622       (InstanceKlass::cast(recv_klass)->is_linked() && !recv_klass->is_interface())) {
 623     if (resolved->is_interface()) {
 624       m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
 625     } else {
 626       m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
 627     }
 628   }
 629 
 630   if (m.is_null()) {
 631     // Return NULL if there was a problem with lookup (uninitialized class, etc.)
 632     return NULL;
 633   }
 634 
 635   oop result = CompilerToVM::get_jvmci_method(m, CHECK_NULL);
 636   return JNIHandles::make_local(THREAD, result);
 637 C2V_END
 638 
 639 C2V_VMENTRY(jboolean, hasFinalizableSubclass,(JNIEnv *, jobject, jobject jvmci_type))
 640   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 641   assert(klass != NULL, "method must not be called for primitive types");
 642   return Dependencies::find_finalizable_subclass(klass) != NULL;
 643 C2V_END
 644 
 645 C2V_VMENTRY(jobject, getClassInitializer, (JNIEnv *, jobject, jobject jvmci_type))
 646   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 647   if (!klass->is_instance_klass()) {
 648     return NULL;
 649   }
 650   InstanceKlass* iklass = InstanceKlass::cast(klass);
 651   oop result = CompilerToVM::get_jvmci_method(iklass->class_initializer(), CHECK_NULL);
 652   return JNIHandles::make_local(THREAD, result);
 653 C2V_END
 654 
 655 C2V_VMENTRY(jlong, getMaxCallTargetOffset, (JNIEnv*, jobject, jlong addr))
 656   address target_addr = (address) addr;
 657   if (target_addr != 0x0) {
 658     int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
 659     int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
 660     return MAX2(ABS(off_low), ABS(off_high));
 661   }
 662   return -1;
 663 C2V_END
 664 
 665 C2V_VMENTRY(void, setNotInlinableOrCompilable,(JNIEnv *, jobject,  jobject jvmci_method))
 666   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 667   method->set_not_c1_compilable();
 668   method->set_not_c2_compilable();
 669   method->set_dont_inline(true);
 670 C2V_END
 671 
 672 C2V_VMENTRY(jint, installCode, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject installed_code, jobject speculation_log))
 673   ResourceMark rm;
 674   HandleMark hm;
 675   JNIHandleMark jni_hm;
 676 
 677   Handle target_handle(THREAD, JNIHandles::resolve(target));
 678   Handle compiled_code_handle(THREAD, JNIHandles::resolve(compiled_code));
 679   CodeBlob* cb = NULL;
 680   Handle installed_code_handle(THREAD, JNIHandles::resolve(installed_code));
 681   Handle speculation_log_handle(THREAD, JNIHandles::resolve(speculation_log));
 682 
 683   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK_JNI_ERR);
 684 
 685   TraceTime install_time("installCode", JVMCICompiler::codeInstallTimer());
 686   bool is_immutable_PIC = HotSpotCompiledCode::isImmutablePIC(compiled_code_handle) > 0;
 687   CodeInstaller installer(is_immutable_PIC);
 688   JVMCIEnv::CodeInstallResult result = installer.install(compiler, target_handle, compiled_code_handle, cb, installed_code_handle, speculation_log_handle, CHECK_0);
 689 
 690   if (PrintCodeCacheOnCompilation) {
 691     stringStream s;
 692     // Dump code cache  into a buffer before locking the tty,
 693     {
 694       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 695       CodeCache::print_summary(&s, false);
 696     }
 697     ttyLocker ttyl;
 698     tty->print_raw_cr(s.as_string());
 699   }
 700 
 701   if (result != JVMCIEnv::ok) {
 702     assert(cb == NULL, "should be");
 703   } else {
 704     if (installed_code_handle.not_null()) {
 705       assert(installed_code_handle->is_a(InstalledCode::klass()), "wrong type");
 706       nmethod::invalidate_installed_code(installed_code_handle, CHECK_0);
 707       {
 708         // Ensure that all updates to the InstalledCode fields are consistent.
 709         MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 710         InstalledCode::set_address(installed_code_handle, (jlong) cb);
 711         InstalledCode::set_version(installed_code_handle, InstalledCode::version(installed_code_handle) + 1);
 712         if (cb->is_nmethod()) {
 713           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->as_nmethod_or_null()->verified_entry_point());
 714         } else {
 715           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->code_begin());
 716         }
 717         if (installed_code_handle->is_a(HotSpotInstalledCode::klass())) {
 718           HotSpotInstalledCode::set_size(installed_code_handle, cb->size());
 719           HotSpotInstalledCode::set_codeStart(installed_code_handle, (jlong) cb->code_begin());
 720           HotSpotInstalledCode::set_codeSize(installed_code_handle, cb->code_size());
 721         }
 722       }
 723     }
 724   }
 725   return result;
 726 C2V_END
 727 
 728 C2V_VMENTRY(jint, getMetadata, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject metadata))
 729 #if INCLUDE_AOT
 730   ResourceMark rm;
 731   HandleMark hm;
 732 
 733   Handle target_handle(THREAD, JNIHandles::resolve(target));
 734   Handle compiled_code_handle(THREAD, JNIHandles::resolve(compiled_code));
 735   Handle metadata_handle(THREAD, JNIHandles::resolve(metadata));
 736 
 737   CodeMetadata code_metadata;
 738   CodeBlob *cb = NULL;
 739   CodeInstaller installer(true /* immutable PIC compilation */);
 740 
 741   JVMCIEnv::CodeInstallResult result = installer.gather_metadata(target_handle, compiled_code_handle, code_metadata, CHECK_0);
 742   if (result != JVMCIEnv::ok) {
 743     return result;
 744   }
 745 
 746   if (code_metadata.get_nr_pc_desc() > 0) {
 747     typeArrayHandle pcArrayOop = oopFactory::new_byteArray_handle(sizeof(PcDesc) * code_metadata.get_nr_pc_desc(), CHECK_(JVMCIEnv::cache_full));
 748     memcpy(pcArrayOop->byte_at_addr(0), code_metadata.get_pc_desc(), sizeof(PcDesc) * code_metadata.get_nr_pc_desc());
 749     HotSpotMetaData::set_pcDescBytes(metadata_handle, pcArrayOop());
 750   }
 751 
 752   if (code_metadata.get_scopes_size() > 0) {
 753     typeArrayHandle scopesArrayOop = oopFactory::new_byteArray_handle(code_metadata.get_scopes_size(), CHECK_(JVMCIEnv::cache_full));
 754     memcpy(scopesArrayOop->byte_at_addr(0), code_metadata.get_scopes_desc(), code_metadata.get_scopes_size());
 755     HotSpotMetaData::set_scopesDescBytes(metadata_handle, scopesArrayOop());
 756   }
 757 
 758   RelocBuffer* reloc_buffer = code_metadata.get_reloc_buffer();
 759   typeArrayHandle relocArrayOop = oopFactory::new_byteArray_handle((int) reloc_buffer->size(), CHECK_(JVMCIEnv::cache_full));
 760   if (reloc_buffer->size() > 0) {
 761     memcpy(relocArrayOop->byte_at_addr(0), reloc_buffer->begin(), reloc_buffer->size());
 762   }
 763   HotSpotMetaData::set_relocBytes(metadata_handle, relocArrayOop());
 764 
 765   const OopMapSet* oopMapSet = installer.oopMapSet();
 766   {
 767     ResourceMark mark;
 768     ImmutableOopMapBuilder builder(oopMapSet);
 769     int oopmap_size = builder.heap_size();
 770     typeArrayHandle oopMapArrayHandle = oopFactory::new_byteArray_handle(oopmap_size, CHECK_(JVMCIEnv::cache_full));
 771     builder.generate_into((address) oopMapArrayHandle->byte_at_addr(0));
 772     HotSpotMetaData::set_oopMaps(metadata_handle, oopMapArrayHandle());
 773   }
 774 
 775   AOTOopRecorder* recorder = code_metadata.get_oop_recorder();
 776 
 777   int nr_meta_refs = recorder->nr_meta_refs();
 778   objArrayOop metadataArray = oopFactory::new_objectArray(nr_meta_refs, CHECK_(JVMCIEnv::cache_full));
 779   objArrayHandle metadataArrayHandle(THREAD, metadataArray);
 780   for (int i = 0; i < nr_meta_refs; ++i) {
 781     jobject element = recorder->meta_element(i);
 782     if (element == NULL) {
 783       return JVMCIEnv::cache_full;
 784     }
 785     metadataArrayHandle->obj_at_put(i, JNIHandles::resolve(element));
 786   }
 787   HotSpotMetaData::set_metadata(metadata_handle, metadataArrayHandle());
 788 
 789   ExceptionHandlerTable* handler = code_metadata.get_exception_table();
 790   int table_size = handler->size_in_bytes();
 791   typeArrayHandle exceptionArrayOop = oopFactory::new_byteArray_handle(table_size, CHECK_(JVMCIEnv::cache_full));
 792 
 793   if (table_size > 0) {
 794     handler->copy_bytes_to((address) exceptionArrayOop->byte_at_addr(0));
 795   }
 796   HotSpotMetaData::set_exceptionBytes(metadata_handle, exceptionArrayOop());
 797 
 798   return result;
 799 #else
 800   THROW_MSG_0(vmSymbols::java_lang_InternalError(), "unimplemented");
 801 #endif
 802 C2V_END
 803 
 804 C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv *jniEnv, jobject))
 805   JVMCICompiler* compiler = JVMCICompiler::instance(true, CHECK);
 806   CompilerStatistics* stats = compiler->stats();
 807   stats->_standard.reset();
 808   stats->_osr.reset();
 809 C2V_END
 810 
 811 C2V_VMENTRY(jobject, disassembleCodeBlob, (JNIEnv *jniEnv, jobject, jobject installedCode))
 812   ResourceMark rm;
 813   HandleMark hm;
 814 
 815   if (installedCode == NULL) {
 816     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), "installedCode is null");
 817   }
 818 
 819   jlong codeBlob = InstalledCode::address(installedCode);
 820   if (codeBlob == 0L) {
 821     return NULL;
 822   }
 823 
 824   CodeBlob* cb = (CodeBlob*) (address) codeBlob;
 825   if (cb == NULL) {
 826     return NULL;
 827   }
 828 
 829   // We don't want the stringStream buffer to resize during disassembly as it
 830   // uses scoped resource memory. If a nested function called during disassembly uses
 831   // a ResourceMark and the buffer expands within the scope of the mark,
 832   // the buffer becomes garbage when that scope is exited. Experience shows that
 833   // the disassembled code is typically about 10x the code size so a fixed buffer
 834   // sized to 20x code size plus a fixed amount for header info should be sufficient.
 835   int bufferSize = cb->code_size() * 20 + 1024;
 836   char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
 837   stringStream st(buffer, bufferSize);
 838   if (cb->is_nmethod()) {
 839     nmethod* nm = (nmethod*) cb;
 840     if (!nm->is_alive()) {
 841       return NULL;
 842     }
 843   }
 844   Disassembler::decode(cb, &st);
 845   if (st.size() <= 0) {
 846     return NULL;
 847   }
 848 
 849   Handle result = java_lang_String::create_from_platform_dependent_str(st.as_string(), CHECK_NULL);
 850   return JNIHandles::make_local(THREAD, result());
 851 C2V_END
 852 
 853 C2V_VMENTRY(jobject, getStackTraceElement, (JNIEnv*, jobject, jobject jvmci_method, int bci))
 854   ResourceMark rm;
 855   HandleMark hm;
 856 
 857   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 858   oop element = java_lang_StackTraceElement::create(method, bci, CHECK_NULL);
 859   return JNIHandles::make_local(THREAD, element);
 860 C2V_END
 861 
 862 C2V_VMENTRY(jobject, executeInstalledCode, (JNIEnv*, jobject, jobject args, jobject hotspotInstalledCode))
 863   ResourceMark rm;
 864   HandleMark hm;
 865 
 866   jlong nmethodValue = InstalledCode::address(hotspotInstalledCode);
 867   if (nmethodValue == 0L) {
 868     THROW_NULL(vmSymbols::jdk_vm_ci_code_InvalidInstalledCodeException());
 869   }
 870   nmethod* nm = (nmethod*) (address) nmethodValue;
 871   methodHandle mh = nm->method();
 872   Symbol* signature = mh->signature();
 873   JavaCallArguments jca(mh->size_of_parameters());
 874 
 875   JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
 876   JavaValue result(jap.get_ret_type());
 877   jca.set_alternative_target(nm);
 878   JavaCalls::call(&result, mh, &jca, CHECK_NULL);
 879 
 880   if (jap.get_ret_type() == T_VOID) {
 881     return NULL;
 882   } else if (jap.get_ret_type() == T_OBJECT || jap.get_ret_type() == T_ARRAY
 883              || jap.get_ret_type() == T_VALUETYPE) {
 884     return JNIHandles::make_local(THREAD, (oop) result.get_jobject());
 885   } else {
 886     jvalue *value = (jvalue *) result.get_value_addr();
 887     // Narrow the value down if required (Important on big endian machines)
 888     switch (jap.get_ret_type()) {
 889       case T_BOOLEAN:
 890        value->z = (jboolean) value->i;
 891        break;
 892       case T_BYTE:
 893        value->b = (jbyte) value->i;
 894        break;
 895       case T_CHAR:
 896        value->c = (jchar) value->i;
 897        break;
 898       case T_SHORT:
 899        value->s = (jshort) value->i;
 900        break;
 901       default:
 902         break;
 903     }
 904     oop o = java_lang_boxing_object::create(jap.get_ret_type(), value, CHECK_NULL);
 905     return JNIHandles::make_local(THREAD, o);
 906   }
 907 C2V_END
 908 
 909 C2V_VMENTRY(jlongArray, getLineNumberTable, (JNIEnv *, jobject, jobject jvmci_method))
 910   Method* method = CompilerToVM::asMethod(jvmci_method);
 911   if (!method->has_linenumber_table()) {
 912     return NULL;
 913   }
 914   u2 num_entries = 0;
 915   CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
 916   while (streamForSize.read_pair()) {
 917     num_entries++;
 918   }
 919 
 920   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
 921   typeArrayOop result = oopFactory::new_longArray(2 * num_entries, CHECK_NULL);
 922 
 923   int i = 0;
 924   jlong value;
 925   while (stream.read_pair()) {
 926     value = ((long) stream.bci());
 927     result->long_at_put(i, value);
 928     value = ((long) stream.line());
 929     result->long_at_put(i + 1, value);
 930     i += 2;
 931   }
 932 
 933   return (jlongArray) JNIHandles::make_local(THREAD, result);
 934 C2V_END
 935 
 936 C2V_VMENTRY(jlong, getLocalVariableTableStart, (JNIEnv *, jobject, jobject jvmci_method))
 937   ResourceMark rm;
 938   Method* method = CompilerToVM::asMethod(jvmci_method);
 939   if (!method->has_localvariable_table()) {
 940     return 0;
 941   }
 942   return (jlong) (address) method->localvariable_table_start();
 943 C2V_END
 944 
 945 C2V_VMENTRY(jint, getLocalVariableTableLength, (JNIEnv *, jobject, jobject jvmci_method))
 946   ResourceMark rm;
 947   Method* method = CompilerToVM::asMethod(jvmci_method);
 948   return method->localvariable_table_length();
 949 C2V_END
 950 
 951 C2V_VMENTRY(void, reprofile, (JNIEnv*, jobject, jobject jvmci_method))
 952   Method* method = CompilerToVM::asMethod(jvmci_method);
 953   MethodCounters* mcs = method->method_counters();
 954   if (mcs != NULL) {
 955     mcs->clear_counters();
 956   }
 957   NOT_PRODUCT(method->set_compiled_invocation_count(0));
 958 
 959   CompiledMethod* code = method->code();
 960   if (code != NULL) {
 961     code->make_not_entrant();
 962   }
 963 
 964   MethodData* method_data = method->method_data();
 965   if (method_data == NULL) {
 966     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 967     method_data = MethodData::allocate(loader_data, method, CHECK);
 968     method->set_method_data(method_data);
 969   } else {
 970     method_data->initialize();
 971   }
 972 C2V_END
 973 
 974 
 975 C2V_VMENTRY(void, invalidateInstalledCode, (JNIEnv*, jobject, jobject installed_code))
 976   Handle installed_code_handle(THREAD, JNIHandles::resolve(installed_code));
 977   nmethod::invalidate_installed_code(installed_code_handle, CHECK);
 978 C2V_END
 979 
 980 C2V_VMENTRY(jlongArray, collectCounters, (JNIEnv*, jobject))
 981   typeArrayOop arrayOop = oopFactory::new_longArray(JVMCICounterSize, CHECK_NULL);
 982   JavaThread::collect_counters(arrayOop);
 983   return (jlongArray) JNIHandles::make_local(THREAD, arrayOop);
 984 C2V_END
 985 
 986 C2V_VMENTRY(int, allocateCompileId, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci))
 987   HandleMark hm;
 988   ResourceMark rm;
 989   if (JNIHandles::resolve(jvmci_method) == NULL) {
 990     THROW_0(vmSymbols::java_lang_NullPointerException());
 991   }
 992   Method* method = CompilerToVM::asMethod(jvmci_method);
 993   if (entry_bci >= method->code_size() || entry_bci < -1) {
 994     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Unexpected bci %d", entry_bci));
 995   }
 996   return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
 997 C2V_END
 998 
 999 
1000 C2V_VMENTRY(jboolean, isMature, (JNIEnv*, jobject, jlong metaspace_method_data))
1001   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
1002   return mdo != NULL && mdo->is_mature();
1003 C2V_END
1004 
1005 C2V_VMENTRY(jboolean, hasCompiledCodeForOSR, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci, int comp_level))
1006   Method* method = CompilerToVM::asMethod(jvmci_method);
1007   return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != NULL;
1008 C2V_END
1009 
1010 C2V_VMENTRY(jobject, getSymbol, (JNIEnv*, jobject, jlong symbol))
1011   Handle sym = java_lang_String::create_from_symbol((Symbol*)(address)symbol, CHECK_NULL);
1012   return JNIHandles::make_local(THREAD, sym());
1013 C2V_END
1014 
1015 bool matches(jobjectArray methods, Method* method) {
1016   objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
1017 
1018   for (int i = 0; i < methods_oop->length(); i++) {
1019     oop resolved = methods_oop->obj_at(i);
1020     if (resolved->is_a(HotSpotResolvedJavaMethodImpl::klass()) && CompilerToVM::asMethod(resolved) == method) {
1021       return true;
1022     }
1023   }
1024   return false;
1025 }
1026 
1027 void call_interface(JavaValue* result, Klass* spec_klass, Symbol* name, Symbol* signature, JavaCallArguments* args, TRAPS) {
1028   CallInfo callinfo;
1029   Handle receiver = args->receiver();
1030   Klass* recvrKlass = receiver.is_null() ? (Klass*)NULL : receiver->klass();
1031   LinkInfo link_info(spec_klass, name, signature);
1032   LinkResolver::resolve_interface_call(
1033           callinfo, receiver, recvrKlass, link_info, true, CHECK);
1034   methodHandle method = callinfo.selected_method();
1035   assert(method.not_null(), "should have thrown exception");
1036 
1037   // Invoke the method
1038   JavaCalls::call(result, method, args, CHECK);
1039 }
1040 
1041 C2V_VMENTRY(jobject, iterateFrames, (JNIEnv*, jobject compilerToVM, jobjectArray initial_methods, jobjectArray match_methods, jint initialSkip, jobject visitor_handle))
1042   ResourceMark rm;
1043 
1044   if (!thread->has_last_Java_frame()) {
1045     return NULL;
1046   }
1047   Handle visitor(THREAD, JNIHandles::resolve_non_null(visitor_handle));
1048   Handle frame_reference = HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1049   HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1050 
1051   StackFrameStream fst(thread);
1052 
1053   jobjectArray methods = initial_methods;
1054 
1055   int frame_number = 0;
1056   vframe* vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1057 
1058   while (true) {
1059     // look for the given method
1060     bool realloc_called = false;
1061     while (true) {
1062       StackValueCollection* locals = NULL;
1063       if (vf->is_compiled_frame()) {
1064         // compiled method frame
1065         compiledVFrame* cvf = compiledVFrame::cast(vf);
1066         if (methods == NULL || matches(methods, cvf->method())) {
1067           if (initialSkip > 0) {
1068             initialSkip--;
1069           } else {
1070             ScopeDesc* scope = cvf->scope();
1071             // native wrappers do not have a scope
1072             if (scope != NULL && scope->objects() != NULL) {
1073               GrowableArray<ScopeValue*>* objects;
1074               if (!realloc_called) {
1075                 objects = scope->objects();
1076               } else {
1077                 // some object might already have been re-allocated, only reallocate the non-allocated ones
1078                 objects = new GrowableArray<ScopeValue*>(scope->objects()->length());
1079                 for (int i = 0; i < scope->objects()->length(); i++) {
1080                   ObjectValue* sv = (ObjectValue*) scope->objects()->at(i);
1081                   if (sv->value().is_null()) {
1082                     objects->append(sv);
1083                   }
1084                 }
1085               }
1086               bool realloc_failures = Deoptimization::realloc_objects(thread, fst.current(), objects, CHECK_NULL);
1087               Deoptimization::reassign_fields(fst.current(), fst.register_map(), objects, realloc_failures, false, CHECK_NULL);
1088               realloc_called = true;
1089 
1090               GrowableArray<ScopeValue*>* local_values = scope->locals();
1091               assert(local_values != NULL, "NULL locals");
1092               typeArrayOop array_oop = oopFactory::new_boolArray(local_values->length(), CHECK_NULL);
1093               typeArrayHandle array(THREAD, array_oop);
1094               for (int i = 0; i < local_values->length(); i++) {
1095                 ScopeValue* value = local_values->at(i);
1096                 if (value->is_object()) {
1097                   array->bool_at_put(i, true);
1098                 }
1099               }
1100               HotSpotStackFrameReference::set_localIsVirtual(frame_reference, array());
1101             } else {
1102               HotSpotStackFrameReference::set_localIsVirtual(frame_reference, NULL);
1103             }
1104 
1105             locals = cvf->locals();
1106             HotSpotStackFrameReference::set_bci(frame_reference, cvf->bci());
1107             oop method = CompilerToVM::get_jvmci_method(cvf->method(), CHECK_NULL);
1108             HotSpotStackFrameReference::set_method(frame_reference, method);
1109           }
1110         }
1111       } else if (vf->is_interpreted_frame()) {
1112         // interpreted method frame
1113         interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1114         if (methods == NULL || matches(methods, ivf->method())) {
1115           if (initialSkip > 0) {
1116             initialSkip--;
1117           } else {
1118             locals = ivf->locals();
1119             HotSpotStackFrameReference::set_bci(frame_reference, ivf->bci());
1120             oop method = CompilerToVM::get_jvmci_method(ivf->method(), CHECK_NULL);
1121             HotSpotStackFrameReference::set_method(frame_reference, method);
1122             HotSpotStackFrameReference::set_localIsVirtual(frame_reference, NULL);
1123           }
1124         }
1125       }
1126 
1127       // locals != NULL means that we found a matching frame and result is already partially initialized
1128       if (locals != NULL) {
1129         methods = match_methods;
1130         HotSpotStackFrameReference::set_compilerToVM(frame_reference, JNIHandles::resolve(compilerToVM));
1131         HotSpotStackFrameReference::set_stackPointer(frame_reference, (jlong) fst.current()->sp());
1132         HotSpotStackFrameReference::set_frameNumber(frame_reference, frame_number);
1133 
1134         // initialize the locals array
1135         objArrayOop array_oop = oopFactory::new_objectArray(locals->size(), CHECK_NULL);
1136         objArrayHandle array(THREAD, array_oop);
1137         for (int i = 0; i < locals->size(); i++) {
1138           StackValue* var = locals->at(i);
1139           if (var->type() == T_OBJECT) {
1140             array->obj_at_put(i, locals->at(i)->get_obj()());
1141           }
1142         }
1143         HotSpotStackFrameReference::set_locals(frame_reference, array());
1144         HotSpotStackFrameReference::set_objectsMaterialized(frame_reference, JNI_FALSE);
1145 
1146         JavaValue result(T_OBJECT);
1147         JavaCallArguments args(visitor);
1148         args.push_oop(frame_reference);
1149         call_interface(&result, SystemDictionary::InspectedFrameVisitor_klass(), vmSymbols::visitFrame_name(), vmSymbols::visitFrame_signature(), &args, CHECK_NULL);
1150         if (result.get_jobject() != NULL) {
1151           return JNIHandles::make_local(thread, (oop) result.get_jobject());
1152         }
1153         assert(initialSkip == 0, "There should be no match before initialSkip == 0");
1154         if (HotSpotStackFrameReference::objectsMaterialized(frame_reference) == JNI_TRUE) {
1155           // the frame has been deoptimized, we need to re-synchronize the frame and vframe
1156           intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(frame_reference);
1157           fst = StackFrameStream(thread);
1158           while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1159             fst.next();
1160           }
1161           if (fst.current()->sp() != stack_pointer) {
1162             THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1163           }
1164           vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1165           if (!vf->is_compiled_frame()) {
1166             THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1167           }
1168           for (int i = 0; i < frame_number; i++) {
1169             if (vf->is_top()) {
1170               THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "vframe not found after deopt")
1171             }
1172             vf = vf->sender();
1173             assert(vf->is_compiled_frame(), "Wrong frame type");
1174           }
1175         }
1176         frame_reference = HotSpotStackFrameReference::klass()->allocate_instance_handle(CHECK_NULL);
1177         HotSpotStackFrameReference::klass()->initialize(CHECK_NULL);
1178       }
1179 
1180       if (vf->is_top()) {
1181         break;
1182       }
1183       frame_number++;
1184       vf = vf->sender();
1185     } // end of vframe loop
1186 
1187     if (fst.is_done()) {
1188       break;
1189     }
1190     fst.next();
1191     vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1192     frame_number = 0;
1193   } // end of frame loop
1194 
1195   // the end was reached without finding a matching method
1196   return NULL;
1197 C2V_END
1198 
1199 C2V_VMENTRY(void, resolveInvokeDynamicInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1200   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1201   CallInfo callInfo;
1202   LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokedynamic, CHECK);
1203   ConstantPoolCacheEntry* cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(index);
1204   cp_cache_entry->set_dynamic_call(cp, callInfo);
1205 C2V_END
1206 
1207 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1208   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1209   Klass* holder = cp->klass_ref_at(index, CHECK);
1210   Symbol* name = cp->name_ref_at(index);
1211   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1212     CallInfo callInfo;
1213     LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1214     ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1215     cp_cache_entry->set_method_handle(cp, callInfo);
1216   }
1217 C2V_END
1218 
1219 C2V_VMENTRY(jint, isResolvedInvokeHandleInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1220   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1221   ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1222   if (cp_cache_entry->is_resolved(Bytecodes::_invokehandle)) {
1223     // MethodHandle.invoke* --> LambdaForm?
1224     ResourceMark rm;
1225 
1226     LinkInfo link_info(cp, index, CATCH);
1227 
1228     Klass* resolved_klass = link_info.resolved_klass();
1229 
1230     Symbol* name_sym = cp->name_ref_at(index);
1231 
1232     vmassert(MethodHandles::is_method_handle_invoke_name(resolved_klass, name_sym), "!");
1233     vmassert(MethodHandles::is_signature_polymorphic_name(resolved_klass, name_sym), "!");
1234 
1235     methodHandle adapter_method(cp_cache_entry->f1_as_method());
1236 
1237     methodHandle resolved_method(adapter_method);
1238 
1239     // Can we treat it as a regular invokevirtual?
1240     if (resolved_method->method_holder() == resolved_klass && resolved_method->name() == name_sym) {
1241       vmassert(!resolved_method->is_static(),"!");
1242       vmassert(MethodHandles::is_signature_polymorphic_method(resolved_method()),"!");
1243       vmassert(!MethodHandles::is_signature_polymorphic_static(resolved_method->intrinsic_id()), "!");
1244       vmassert(cp_cache_entry->appendix_if_resolved(cp) == NULL, "!");
1245 
1246       methodHandle m(LinkResolver::linktime_resolve_virtual_method_or_null(link_info));
1247       vmassert(m == resolved_method, "!!");
1248       return -1;
1249     }
1250 
1251     return Bytecodes::_invokevirtual;
1252   }
1253   if (cp_cache_entry->is_resolved(Bytecodes::_invokedynamic)) {
1254     return Bytecodes::_invokedynamic;
1255   }
1256   return -1;
1257 C2V_END
1258 
1259 
1260 C2V_VMENTRY(jobject, getSignaturePolymorphicHolders, (JNIEnv*, jobject))
1261   objArrayHandle holders = oopFactory::new_objArray_handle(SystemDictionary::String_klass(), 2, CHECK_NULL);
1262   Handle mh = java_lang_String::create_from_str("Ljava/lang/invoke/MethodHandle;", CHECK_NULL);
1263   Handle vh = java_lang_String::create_from_str("Ljava/lang/invoke/VarHandle;", CHECK_NULL);
1264   holders->obj_at_put(0, mh());
1265   holders->obj_at_put(1, vh());
1266   return JNIHandles::make_local(THREAD, holders());
1267 C2V_END
1268 
1269 C2V_VMENTRY(jboolean, shouldDebugNonSafepoints, (JNIEnv*, jobject))
1270   //see compute_recording_non_safepoints in debugInfroRec.cpp
1271   if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1272     return true;
1273   }
1274   return DebugNonSafepoints;
1275 C2V_END
1276 
1277 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1278 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv*, jobject, jobject hs_frame, bool invalidate))
1279   ResourceMark rm;
1280 
1281   if (hs_frame == NULL) {
1282     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "stack frame is null")
1283   }
1284 
1285   HotSpotStackFrameReference::klass()->initialize(CHECK);
1286 
1287   // look for the given stack frame
1288   StackFrameStream fst(thread);
1289   intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(hs_frame);
1290   while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1291     fst.next();
1292   }
1293   if (fst.current()->sp() != stack_pointer) {
1294     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found")
1295   }
1296 
1297   if (invalidate) {
1298     if (!fst.current()->is_compiled_frame()) {
1299       THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1300     }
1301     assert(fst.current()->cb()->is_nmethod(), "nmethod expected");
1302     ((nmethod*) fst.current()->cb())->make_not_entrant();
1303   }
1304   Deoptimization::deoptimize(thread, *fst.current(), fst.register_map(), Deoptimization::Reason_none);
1305   // look for the frame again as it has been updated by deopt (pc, deopt state...)
1306   StackFrameStream fstAfterDeopt(thread);
1307   while (fstAfterDeopt.current()->sp() != stack_pointer && !fstAfterDeopt.is_done()) {
1308     fstAfterDeopt.next();
1309   }
1310   if (fstAfterDeopt.current()->sp() != stack_pointer) {
1311     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1312   }
1313 
1314   vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1315   if (!vf->is_compiled_frame()) {
1316     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1317   }
1318 
1319   GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1320   while (true) {
1321     assert(vf->is_compiled_frame(), "Wrong frame type");
1322     virtualFrames->push(compiledVFrame::cast(vf));
1323     if (vf->is_top()) {
1324       break;
1325     }
1326     vf = vf->sender();
1327   }
1328 
1329   int last_frame_number = HotSpotStackFrameReference::frameNumber(hs_frame);
1330   if (last_frame_number >= virtualFrames->length()) {
1331     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "invalid frame number")
1332   }
1333 
1334   // Reallocate the non-escaping objects and restore their fields.
1335   assert (virtualFrames->at(last_frame_number)->scope() != NULL,"invalid scope");
1336   GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1337 
1338   if (objects == NULL) {
1339     // no objects to materialize
1340     return;
1341   }
1342 
1343   bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), objects, CHECK);
1344   Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false, THREAD);
1345 
1346   for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1347     compiledVFrame* cvf = virtualFrames->at(frame_index);
1348 
1349     GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
1350     StackValueCollection* locals = cvf->locals();
1351     if (locals != NULL) {
1352       for (int i2 = 0; i2 < locals->size(); i2++) {
1353         StackValue* var = locals->at(i2);
1354         if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) {
1355           jvalue val;
1356           val.l = (jobject) locals->at(i2)->get_obj()();
1357           cvf->update_local(T_OBJECT, i2, val);
1358         }
1359       }
1360     }
1361 
1362     GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
1363     StackValueCollection* expressions = cvf->expressions();
1364     if (expressions != NULL) {
1365       for (int i2 = 0; i2 < expressions->size(); i2++) {
1366         StackValue* var = expressions->at(i2);
1367         if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
1368           jvalue val;
1369           val.l = (jobject) expressions->at(i2)->get_obj()();
1370           cvf->update_stack(T_OBJECT, i2, val);
1371         }
1372       }
1373     }
1374 
1375     GrowableArray<MonitorValue*>* scopeMonitors = cvf->scope()->monitors();
1376     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1377     if (monitors != NULL) {
1378       for (int i2 = 0; i2 < monitors->length(); i2++) {
1379         cvf->update_monitor(i2, monitors->at(i2));
1380       }
1381     }
1382   }
1383 
1384   // all locals are materialized by now
1385   HotSpotStackFrameReference::set_localIsVirtual(hs_frame, NULL);
1386 
1387   // update the locals array
1388   objArrayHandle array(THREAD, HotSpotStackFrameReference::locals(hs_frame));
1389   StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1390   for (int i = 0; i < locals->size(); i++) {
1391     StackValue* var = locals->at(i);
1392     if (var->type() == T_OBJECT) {
1393       array->obj_at_put(i, locals->at(i)->get_obj()());
1394     }
1395   }
1396   HotSpotStackFrameReference::set_objectsMaterialized(hs_frame, JNI_TRUE);
1397 C2V_END
1398 
1399 C2V_VMENTRY(void, writeDebugOutput, (JNIEnv*, jobject, jbyteArray bytes, jint offset, jint length))
1400   if (bytes == NULL) {
1401     THROW(vmSymbols::java_lang_NullPointerException());
1402   }
1403   typeArrayOop array = (typeArrayOop) JNIHandles::resolve(bytes);
1404 
1405   // Check if offset and length are non negative.
1406   if (offset < 0 || length < 0) {
1407     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1408   }
1409   // Check if the range is valid.
1410   if ((((unsigned int) length + (unsigned int) offset) > (unsigned int) array->length())) {
1411     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1412   }
1413   while (length > 0) {
1414     jbyte* start = array->byte_at_addr(offset);
1415     tty->write((char*) start, MIN2(length, (jint)O_BUFLEN));
1416     length -= O_BUFLEN;
1417     offset += O_BUFLEN;
1418   }
1419 C2V_END
1420 
1421 C2V_VMENTRY(void, flushDebugOutput, (JNIEnv*, jobject))
1422   tty->flush();
1423 C2V_END
1424 
1425 C2V_VMENTRY(int, methodDataProfileDataSize, (JNIEnv*, jobject, jlong metaspace_method_data, jint position))
1426   ResourceMark rm;
1427   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
1428   ProfileData* profile_data = mdo->data_at(position);
1429   if (mdo->is_valid(profile_data)) {
1430     return profile_data->size_in_bytes();
1431   }
1432   DataLayout* data    = mdo->extra_data_base();
1433   DataLayout* end   = mdo->extra_data_limit();
1434   for (;; data = mdo->next_extra(data)) {
1435     assert(data < end, "moved past end of extra data");
1436     profile_data = data->data_in();
1437     if (mdo->dp_to_di(profile_data->dp()) == position) {
1438       return profile_data->size_in_bytes();
1439     }
1440   }
1441   THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Invalid profile data position %d", position));
1442 C2V_END
1443 
1444 C2V_VMENTRY(jlong, getFingerprint, (JNIEnv*, jobject, jlong metaspace_klass))
1445 #if INCLUDE_AOT
1446   Klass *k = CompilerToVM::asKlass(metaspace_klass);
1447   if (k->is_instance_klass()) {
1448     return InstanceKlass::cast(k)->get_stored_fingerprint();
1449   } else {
1450     return 0;
1451   }
1452 #else
1453   THROW_MSG_0(vmSymbols::java_lang_InternalError(), "unimplemented");
1454 #endif
1455 C2V_END
1456 
1457 C2V_VMENTRY(jobject, getHostClass, (JNIEnv*, jobject, jobject jvmci_type))
1458   InstanceKlass* k = InstanceKlass::cast(CompilerToVM::asKlass(jvmci_type));
1459   InstanceKlass* host = k->unsafe_anonymous_host();
1460   JVMCIKlassHandle handle(THREAD, host);
1461   oop result = CompilerToVM::get_jvmci_type(handle, CHECK_NULL);
1462   return JNIHandles::make_local(THREAD, result);
1463 C2V_END
1464 
1465 C2V_VMENTRY(int, interpreterFrameSize, (JNIEnv*, jobject, jobject bytecode_frame_handle))
1466   if (bytecode_frame_handle == NULL) {
1467     THROW_0(vmSymbols::java_lang_NullPointerException());
1468   }
1469 
1470   oop top_bytecode_frame = JNIHandles::resolve_non_null(bytecode_frame_handle);
1471   oop bytecode_frame = top_bytecode_frame;
1472   int size = 0;
1473   int callee_parameters = 0;
1474   int callee_locals = 0;
1475   Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1476   int extra_args = method->max_stack() - BytecodeFrame::numStack(bytecode_frame);
1477 
1478   while (bytecode_frame != NULL) {
1479     int locks = BytecodeFrame::numLocks(bytecode_frame);
1480     int temps = BytecodeFrame::numStack(bytecode_frame);
1481     bool is_top_frame = (bytecode_frame == top_bytecode_frame);
1482     Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1483 
1484     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
1485                                                                  temps + callee_parameters,
1486                                                                  extra_args,
1487                                                                  locks,
1488                                                                  callee_parameters,
1489                                                                  callee_locals,
1490                                                                  is_top_frame);
1491     size += frame_size;
1492 
1493     callee_parameters = method->size_of_parameters();
1494     callee_locals = method->max_locals();
1495     extra_args = 0;
1496     bytecode_frame = BytecodePosition::caller(bytecode_frame);
1497   }
1498   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
1499 C2V_END
1500 
1501 C2V_VMENTRY(void, compileToBytecode, (JNIEnv*, jobject, jobject lambda_form_handle))
1502   Handle lambda_form(THREAD, JNIHandles::resolve_non_null(lambda_form_handle));
1503   if (lambda_form->is_a(SystemDictionary::LambdaForm_klass())) {
1504     TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode", CHECK);
1505     JavaValue result(T_VOID);
1506     JavaCalls::call_special(&result, lambda_form, SystemDictionary::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
1507   } else {
1508     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1509                 err_msg("Unexpected type: %s", lambda_form->klass()->external_name()));
1510   }
1511 C2V_END
1512 
1513 C2V_VMENTRY(jobject, asReflectionExecutable, (JNIEnv* env, jobject, jobject jvmci_method))
1514   methodHandle m = CompilerToVM::asMethod(jvmci_method);
1515   oop executable;
1516   if (m->is_class_initializer()) {
1517     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1518         "Cannot create java.lang.reflect.Method for class initializer");
1519   } else if (m->is_object_constructor()) {
1520     executable = Reflection::new_constructor(m, CHECK_NULL);
1521   } else {
1522     executable = Reflection::new_method(m, false, CHECK_NULL);
1523   }
1524   return JNIHandles::make_local(thread, executable);
1525 }
1526 
1527 C2V_VMENTRY(jobject, asReflectionField, (JNIEnv* env, jobject, jobject jvmci_type, jint index))
1528   Klass* klass = CompilerToVM::asKlass(jvmci_type);
1529   if (!klass->is_instance_klass()) {
1530     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1531         err_msg("Expected non-primitive type, got %s", klass->external_name()));
1532   }
1533   InstanceKlass* iklass = InstanceKlass::cast(klass);
1534   Array<u2>* fields = iklass->fields();
1535   if (index < 0 || index > fields->length()) {
1536     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1537         err_msg("Field index %d out of bounds for %s", index, klass->external_name()));
1538   }
1539   fieldDescriptor fd(iklass, index);
1540   oop reflected = Reflection::new_field(&fd, CHECK_NULL);
1541   return JNIHandles::make_local(env, reflected);
1542 }
1543 
1544 #define CC (char*)  /*cast a literal from (const char*)*/
1545 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
1546 
1547 #define STRING                  "Ljava/lang/String;"
1548 #define OBJECT                  "Ljava/lang/Object;"
1549 #define CLASS                   "Ljava/lang/Class;"
1550 #define EXECUTABLE              "Ljava/lang/reflect/Executable;"
1551 #define STACK_TRACE_ELEMENT     "Ljava/lang/StackTraceElement;"
1552 #define INSTALLED_CODE          "Ljdk/vm/ci/code/InstalledCode;"
1553 #define TARGET_DESCRIPTION      "Ljdk/vm/ci/code/TargetDescription;"
1554 #define BYTECODE_FRAME          "Ljdk/vm/ci/code/BytecodeFrame;"
1555 #define INSPECTED_FRAME_VISITOR "Ljdk/vm/ci/code/stack/InspectedFrameVisitor;"
1556 #define RESOLVED_METHOD         "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
1557 #define HS_RESOLVED_METHOD      "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
1558 #define HS_RESOLVED_KLASS       "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
1559 #define HS_CONSTANT_POOL        "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
1560 #define HS_COMPILED_CODE        "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
1561 #define HS_CONFIG               "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
1562 #define HS_METADATA             "Ljdk/vm/ci/hotspot/HotSpotMetaData;"
1563 #define HS_STACK_FRAME_REF      "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
1564 #define HS_SPECULATION_LOG      "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
1565 #define REFLECTION_EXECUTABLE   "Ljava/lang/reflect/Executable;"
1566 #define REFLECTION_FIELD        "Ljava/lang/reflect/Field;"
1567 #define METASPACE_METHOD_DATA   "J"
1568 
1569 JNINativeMethod CompilerToVM::methods[] = {
1570   {CC "getBytecode",                                  CC "(" HS_RESOLVED_METHOD ")[B",                                                      FN_PTR(getBytecode)},
1571   {CC "getExceptionTableStart",                       CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getExceptionTableStart)},
1572   {CC "getExceptionTableLength",                      CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getExceptionTableLength)},
1573   {CC "findUniqueConcreteMethod",                     CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")" HS_RESOLVED_METHOD,                   FN_PTR(findUniqueConcreteMethod)},
1574   {CC "getImplementor",                               CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS,                                       FN_PTR(getImplementor)},
1575   {CC "getStackTraceElement",                         CC "(" HS_RESOLVED_METHOD "I)" STACK_TRACE_ELEMENT,                                   FN_PTR(getStackTraceElement)},
1576   {CC "methodIsIgnoredBySecurityStackWalk",           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(methodIsIgnoredBySecurityStackWalk)},
1577   {CC "setNotInlinableOrCompilable",                  CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(setNotInlinableOrCompilable)},
1578   {CC "isCompilable",                                 CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(isCompilable)},
1579   {CC "hasNeverInlineDirective",                      CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(hasNeverInlineDirective)},
1580   {CC "shouldInlineMethod",                           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(shouldInlineMethod)},
1581   {CC "lookupType",                                   CC "(" STRING CLASS "Z)" HS_RESOLVED_KLASS,                                           FN_PTR(lookupType)},
1582   {CC "lookupNameInPool",                             CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupNameInPool)},
1583   {CC "lookupNameAndTypeRefIndexInPool",              CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupNameAndTypeRefIndexInPool)},
1584   {CC "lookupSignatureInPool",                        CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupSignatureInPool)},
1585   {CC "lookupKlassRefIndexInPool",                    CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupKlassRefIndexInPool)},
1586   {CC "lookupKlassInPool",                            CC "(" HS_CONSTANT_POOL "I)Ljava/lang/Object;",                                       FN_PTR(lookupKlassInPool)},
1587   {CC "lookupAppendixInPool",                         CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(lookupAppendixInPool)},
1588   {CC "lookupMethodInPool",                           CC "(" HS_CONSTANT_POOL "IB)" HS_RESOLVED_METHOD,                                     FN_PTR(lookupMethodInPool)},
1589   {CC "constantPoolRemapInstructionOperandFromCache", CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(constantPoolRemapInstructionOperandFromCache)},
1590   {CC "resolveConstantInPool",                        CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolveConstantInPool)},
1591   {CC "resolvePossiblyCachedConstantInPool",          CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolvePossiblyCachedConstantInPool)},
1592   {CC "resolveTypeInPool",                            CC "(" HS_CONSTANT_POOL "I)" HS_RESOLVED_KLASS,                                       FN_PTR(resolveTypeInPool)},
1593   {CC "resolveFieldInPool",                           CC "(" HS_CONSTANT_POOL "I" HS_RESOLVED_METHOD "B[I)" HS_RESOLVED_KLASS,              FN_PTR(resolveFieldInPool)},
1594   {CC "resolveInvokeDynamicInPool",                   CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeDynamicInPool)},
1595   {CC "resolveInvokeHandleInPool",                    CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeHandleInPool)},
1596   {CC "isResolvedInvokeHandleInPool",                 CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(isResolvedInvokeHandleInPool)},
1597   {CC "resolveMethod",                                CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD, FN_PTR(resolveMethod)},
1598   {CC "getSignaturePolymorphicHolders",               CC "()[" STRING,                                                                      FN_PTR(getSignaturePolymorphicHolders)},
1599   {CC "getVtableIndexForInterfaceMethod",             CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")I",                                     FN_PTR(getVtableIndexForInterfaceMethod)},
1600   {CC "getClassInitializer",                          CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD,                                      FN_PTR(getClassInitializer)},
1601   {CC "hasFinalizableSubclass",                       CC "(" HS_RESOLVED_KLASS ")Z",                                                        FN_PTR(hasFinalizableSubclass)},
1602   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
1603   {CC "asResolvedJavaMethod",                         CC "(" EXECUTABLE ")" HS_RESOLVED_METHOD,                                             FN_PTR(asResolvedJavaMethod)},
1604   {CC "getResolvedJavaMethod",                        CC "(Ljava/lang/Object;J)" HS_RESOLVED_METHOD,                                        FN_PTR(getResolvedJavaMethod)},
1605   {CC "getConstantPool",                              CC "(Ljava/lang/Object;)" HS_CONSTANT_POOL,                                           FN_PTR(getConstantPool)},
1606   {CC "getResolvedJavaType",                          CC "(Ljava/lang/Object;JZ)" HS_RESOLVED_KLASS,                                        FN_PTR(getResolvedJavaType)},
1607   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
1608   {CC "installCode",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE INSTALLED_CODE HS_SPECULATION_LOG ")I",    FN_PTR(installCode)},
1609   {CC "getMetadata",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE HS_METADATA ")I",                          FN_PTR(getMetadata)},
1610   {CC "resetCompilationStatistics",                   CC "()V",                                                                             FN_PTR(resetCompilationStatistics)},
1611   {CC "disassembleCodeBlob",                          CC "(" INSTALLED_CODE ")" STRING,                                                     FN_PTR(disassembleCodeBlob)},
1612   {CC "executeInstalledCode",                         CC "([" OBJECT INSTALLED_CODE ")" OBJECT,                                             FN_PTR(executeInstalledCode)},
1613   {CC "getLineNumberTable",                           CC "(" HS_RESOLVED_METHOD ")[J",                                                      FN_PTR(getLineNumberTable)},
1614   {CC "getLocalVariableTableStart",                   CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getLocalVariableTableStart)},
1615   {CC "getLocalVariableTableLength",                  CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getLocalVariableTableLength)},
1616   {CC "reprofile",                                    CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(reprofile)},
1617   {CC "invalidateInstalledCode",                      CC "(" INSTALLED_CODE ")V",                                                           FN_PTR(invalidateInstalledCode)},
1618   {CC "collectCounters",                              CC "()[J",                                                                            FN_PTR(collectCounters)},
1619   {CC "allocateCompileId",                            CC "(" HS_RESOLVED_METHOD "I)I",                                                      FN_PTR(allocateCompileId)},
1620   {CC "isMature",                                     CC "(" METASPACE_METHOD_DATA ")Z",                                                    FN_PTR(isMature)},
1621   {CC "hasCompiledCodeForOSR",                        CC "(" HS_RESOLVED_METHOD "II)Z",                                                     FN_PTR(hasCompiledCodeForOSR)},
1622   {CC "getSymbol",                                    CC "(J)" STRING,                                                                      FN_PTR(getSymbol)},
1623   {CC "iterateFrames",                                CC "([" RESOLVED_METHOD "[" RESOLVED_METHOD "I" INSPECTED_FRAME_VISITOR ")" OBJECT,   FN_PTR(iterateFrames)},
1624   {CC "materializeVirtualObjects",                    CC "(" HS_STACK_FRAME_REF "Z)V",                                                      FN_PTR(materializeVirtualObjects)},
1625   {CC "shouldDebugNonSafepoints",                     CC "()Z",                                                                             FN_PTR(shouldDebugNonSafepoints)},
1626   {CC "writeDebugOutput",                             CC "([BII)V",                                                                         FN_PTR(writeDebugOutput)},
1627   {CC "flushDebugOutput",                             CC "()V",                                                                             FN_PTR(flushDebugOutput)},
1628   {CC "methodDataProfileDataSize",                    CC "(JI)I",                                                                           FN_PTR(methodDataProfileDataSize)},
1629   {CC "getFingerprint",                               CC "(J)J",                                                                            FN_PTR(getFingerprint)},
1630   {CC "getHostClass",                                 CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS,                                       FN_PTR(getHostClass)},
1631   {CC "interpreterFrameSize",                         CC "(" BYTECODE_FRAME ")I",                                                           FN_PTR(interpreterFrameSize)},
1632   {CC "compileToBytecode",                            CC "(" OBJECT ")V",                                                                   FN_PTR(compileToBytecode)},
1633   {CC "getFlagValue",                                 CC "(" STRING ")" OBJECT,                                                             FN_PTR(getFlagValue)},
1634   {CC "asReflectionExecutable",                       CC "(" HS_RESOLVED_METHOD ")" REFLECTION_EXECUTABLE,                                  FN_PTR(asReflectionExecutable)},
1635   {CC "asReflectionField",                            CC "(" HS_RESOLVED_KLASS "I)" REFLECTION_FIELD,                                       FN_PTR(asReflectionField)},
1636 };
1637 
1638 int CompilerToVM::methods_count() {
1639   return sizeof(methods) / sizeof(JNINativeMethod);
1640 }