1 /*
   2  * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/scopeDesc.hpp"
  28 #include "interpreter/linkResolver.hpp"
  29 #include "memory/oopFactory.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/generateOopMap.hpp"
  32 #include "oops/fieldStreams.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "oops/objArrayOop.inline.hpp"
  35 #include "runtime/fieldDescriptor.hpp"
  36 #include "runtime/javaCalls.hpp"
  37 #include "jvmci/jvmciRuntime.hpp"
  38 #include "compiler/abstractCompiler.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "compiler/compilerOracle.hpp"
  41 #include "compiler/disassembler.hpp"
  42 #include "compiler/oopMap.hpp"
  43 #include "jvmci/jvmciCompilerToVM.hpp"
  44 #include "jvmci/jvmciCompiler.hpp"
  45 #include "jvmci/jvmciEnv.hpp"
  46 #include "jvmci/jvmciJavaClasses.hpp"
  47 #include "jvmci/jvmciCodeInstaller.hpp"
  48 #include "jvmci/vmStructs_jvmci.hpp"
  49 #include "gc/g1/heapRegion.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/deoptimization.hpp"
  52 #include "runtime/timerTrace.hpp"
  53 #include "runtime/vframe.hpp"
  54 #include "runtime/vframe_hp.hpp"
  55 #include "runtime/vmStructs.hpp"
  56 
  57 
  58 // Entry to native method implementation that transitions current thread to '_thread_in_vm'.
  59 #define C2V_VMENTRY(result_type, name, signature) \
  60   JNIEXPORT result_type JNICALL c2v_ ## name signature { \
  61   TRACE_jvmci_1("CompilerToVM::" #name); \
  62   TRACE_CALL(result_type, jvmci_ ## name signature) \
  63   JVMCI_VM_ENTRY_MARK; \
  64 
  65 #define C2V_END }
  66 
  67 oop CompilerToVM::get_jvmci_method(const methodHandle& method, TRAPS) {
  68   if (method() != NULL) {
  69     JavaValue result(T_OBJECT);
  70     JavaCallArguments args;
  71     args.push_long((jlong) (address) method());
  72     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedJavaMethodImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::method_fromMetaspace_signature(), &args, CHECK_NULL);
  73 
  74     return (oop)result.get_jobject();
  75   }
  76   return NULL;
  77 }
  78 
  79 oop CompilerToVM::get_jvmci_type(KlassHandle klass, TRAPS) {
  80   if (klass() != NULL) {
  81     JavaValue result(T_OBJECT);
  82     JavaCallArguments args;
  83     args.push_oop(klass->java_mirror());
  84     JavaCalls::call_static(&result, SystemDictionary::HotSpotResolvedObjectTypeImpl_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::klass_fromMetaspace_signature(), &args, CHECK_NULL);
  85 
  86     return (oop)result.get_jobject();
  87   }
  88   return NULL;
  89 }
  90 
  91 int CompilerToVM::Data::Klass_vtable_start_offset;
  92 int CompilerToVM::Data::Klass_vtable_length_offset;
  93 
  94 int CompilerToVM::Data::Method_extra_stack_entries;
  95 
  96 address CompilerToVM::Data::SharedRuntime_ic_miss_stub;
  97 address CompilerToVM::Data::SharedRuntime_handle_wrong_method_stub;
  98 address CompilerToVM::Data::SharedRuntime_deopt_blob_unpack;
  99 address CompilerToVM::Data::SharedRuntime_deopt_blob_uncommon_trap;
 100 
 101 size_t CompilerToVM::Data::ThreadLocalAllocBuffer_alignment_reserve;
 102 
 103 CollectedHeap* CompilerToVM::Data::Universe_collectedHeap;
 104 int CompilerToVM::Data::Universe_base_vtable_size;
 105 address CompilerToVM::Data::Universe_narrow_oop_base;
 106 int CompilerToVM::Data::Universe_narrow_oop_shift;
 107 address CompilerToVM::Data::Universe_narrow_klass_base;
 108 int CompilerToVM::Data::Universe_narrow_klass_shift;
 109 void* CompilerToVM::Data::Universe_non_oop_bits;
 110 uintptr_t CompilerToVM::Data::Universe_verify_oop_mask;
 111 uintptr_t CompilerToVM::Data::Universe_verify_oop_bits;
 112 
 113 bool       CompilerToVM::Data::_supports_inline_contig_alloc;
 114 HeapWord** CompilerToVM::Data::_heap_end_addr;
 115 HeapWord* volatile* CompilerToVM::Data::_heap_top_addr;
 116 int CompilerToVM::Data::_max_oop_map_stack_offset;
 117 
 118 jbyte* CompilerToVM::Data::cardtable_start_address;
 119 int CompilerToVM::Data::cardtable_shift;
 120 
 121 int CompilerToVM::Data::vm_page_size;
 122 
 123 address CompilerToVM::Data::dsin;
 124 address CompilerToVM::Data::dcos;
 125 address CompilerToVM::Data::dtan;
 126 address CompilerToVM::Data::dexp;
 127 address CompilerToVM::Data::dlog;
 128 address CompilerToVM::Data::dlog10;
 129 address CompilerToVM::Data::dpow;
 130 
 131 void CompilerToVM::Data::initialize() {
 132   Klass_vtable_start_offset = in_bytes(Klass::vtable_start_offset());
 133   Klass_vtable_length_offset = in_bytes(Klass::vtable_length_offset());
 134 
 135   Method_extra_stack_entries = Method::extra_stack_entries();
 136 
 137   SharedRuntime_ic_miss_stub = SharedRuntime::get_ic_miss_stub();
 138   SharedRuntime_handle_wrong_method_stub = SharedRuntime::get_handle_wrong_method_stub();
 139   SharedRuntime_deopt_blob_unpack = SharedRuntime::deopt_blob()->unpack();
 140   SharedRuntime_deopt_blob_uncommon_trap = SharedRuntime::deopt_blob()->uncommon_trap();
 141 
 142   ThreadLocalAllocBuffer_alignment_reserve = ThreadLocalAllocBuffer::alignment_reserve();
 143 
 144   Universe_collectedHeap = Universe::heap();
 145   Universe_base_vtable_size = Universe::base_vtable_size();
 146   Universe_narrow_oop_base = Universe::narrow_oop_base();
 147   Universe_narrow_oop_shift = Universe::narrow_oop_shift();
 148   Universe_narrow_klass_base = Universe::narrow_klass_base();
 149   Universe_narrow_klass_shift = Universe::narrow_klass_shift();
 150   Universe_non_oop_bits = Universe::non_oop_word();
 151   Universe_verify_oop_mask = Universe::verify_oop_mask();
 152   Universe_verify_oop_bits = Universe::verify_oop_bits();
 153 
 154   _supports_inline_contig_alloc = Universe::heap()->supports_inline_contig_alloc();
 155   _heap_end_addr = _supports_inline_contig_alloc ? Universe::heap()->end_addr() : (HeapWord**) -1;
 156   _heap_top_addr = _supports_inline_contig_alloc ? Universe::heap()->top_addr() : (HeapWord* volatile*) -1;
 157 
 158   _max_oop_map_stack_offset = (OopMapValue::register_mask - VMRegImpl::stack2reg(0)->value()) * VMRegImpl::stack_slot_size;
 159   int max_oop_map_stack_index = _max_oop_map_stack_offset / VMRegImpl::stack_slot_size;
 160   assert(OopMapValue::legal_vm_reg_name(VMRegImpl::stack2reg(max_oop_map_stack_index)), "should be valid");
 161   assert(!OopMapValue::legal_vm_reg_name(VMRegImpl::stack2reg(max_oop_map_stack_index + 1)), "should be invalid");
 162 
 163   BarrierSet* bs = Universe::heap()->barrier_set();
 164   switch (bs->kind()) {
 165   case BarrierSet::CardTableModRef:
 166   case BarrierSet::CardTableForRS:
 167   case BarrierSet::CardTableExtension:
 168   case BarrierSet::G1SATBCT:
 169   case BarrierSet::G1SATBCTLogging: {
 170     jbyte* base = barrier_set_cast<CardTableModRefBS>(bs)->byte_map_base;
 171     assert(base != 0, "unexpected byte_map_base");
 172     cardtable_start_address = base;
 173     cardtable_shift = CardTableModRefBS::card_shift;
 174     break;
 175   }
 176   case BarrierSet::ModRef:

 177     cardtable_start_address = 0;
 178     cardtable_shift = 0;
 179     // No post barriers
 180     break;
 181   default:
 182     ShouldNotReachHere();
 183     break;
 184   }
 185 
 186   vm_page_size = os::vm_page_size();
 187 
 188 #define SET_TRIGFUNC(name)                                      \
 189   if (StubRoutines::name() != NULL) {                           \
 190     name = StubRoutines::name();                                \
 191   } else {                                                      \
 192     name = CAST_FROM_FN_PTR(address, SharedRuntime::name);      \
 193   }
 194 
 195   SET_TRIGFUNC(dsin);
 196   SET_TRIGFUNC(dcos);
 197   SET_TRIGFUNC(dtan);
 198   SET_TRIGFUNC(dexp);
 199   SET_TRIGFUNC(dlog10);
 200   SET_TRIGFUNC(dlog);
 201   SET_TRIGFUNC(dpow);
 202 
 203 #undef SET_TRIGFUNC
 204 }
 205 
 206 objArrayHandle CompilerToVM::initialize_intrinsics(TRAPS) {
 207   objArrayHandle vmIntrinsics = oopFactory::new_objArray(VMIntrinsicMethod::klass(), (vmIntrinsics::ID_LIMIT - 1), CHECK_(objArrayHandle()));
 208   int index = 0;
 209   // The intrinsics for a class are usually adjacent to each other.
 210   // When they are, the string for the class name can be reused.
 211   vmSymbols::SID kls_sid = vmSymbols::NO_SID;
 212   Handle kls_str;
 213 #define SID_ENUM(n) vmSymbols::VM_SYMBOL_ENUM_NAME(n)
 214 #define VM_SYMBOL_TO_STRING(s) \
 215   java_lang_String::create_from_symbol(vmSymbols::symbol_at(SID_ENUM(s)), CHECK_(objArrayHandle()))
 216 #define VM_INTRINSIC_INFO(id, kls, name, sig, ignore_fcode) {             \
 217     instanceHandle vmIntrinsicMethod = InstanceKlass::cast(VMIntrinsicMethod::klass())->allocate_instance_handle(CHECK_(objArrayHandle())); \
 218     if (kls_sid != SID_ENUM(kls)) {                                       \
 219       kls_str = VM_SYMBOL_TO_STRING(kls);                                 \
 220       kls_sid = SID_ENUM(kls);                                            \
 221     }                                                                     \
 222     Handle name_str = VM_SYMBOL_TO_STRING(name);                          \
 223     Handle sig_str = VM_SYMBOL_TO_STRING(sig);                            \
 224     VMIntrinsicMethod::set_declaringClass(vmIntrinsicMethod, kls_str());  \
 225     VMIntrinsicMethod::set_name(vmIntrinsicMethod, name_str());           \
 226     VMIntrinsicMethod::set_descriptor(vmIntrinsicMethod, sig_str());      \
 227     VMIntrinsicMethod::set_id(vmIntrinsicMethod, vmIntrinsics::id);       \
 228       vmIntrinsics->obj_at_put(index++, vmIntrinsicMethod());             \
 229   }
 230 
 231   VM_INTRINSICS_DO(VM_INTRINSIC_INFO, VM_SYMBOL_IGNORE, VM_SYMBOL_IGNORE, VM_SYMBOL_IGNORE, VM_ALIAS_IGNORE)
 232 #undef SID_ENUM
 233 #undef VM_SYMBOL_TO_STRING
 234 #undef VM_INTRINSIC_INFO
 235   assert(index == vmIntrinsics::ID_LIMIT - 1, "must be");
 236 
 237   return vmIntrinsics;
 238 }
 239 
 240 C2V_VMENTRY(jobjectArray, readConfiguration, (JNIEnv *env))
 241 #define BOXED_LONG(name, value) oop name; do { jvalue p; p.j = (jlong) (value); name = java_lang_boxing_object::create(T_LONG, &p, CHECK_NULL);} while(0)
 242 #define BOXED_DOUBLE(name, value) oop name; do { jvalue p; p.d = (jdouble) (value); name = java_lang_boxing_object::create(T_DOUBLE, &p, CHECK_NULL);} while(0)
 243   ResourceMark rm;
 244   HandleMark hm;
 245 
 246   CompilerToVM::Data::initialize();
 247 
 248   VMField::klass()->initialize(CHECK_NULL);
 249   VMFlag::klass()->initialize(CHECK_NULL);
 250   VMIntrinsicMethod::klass()->initialize(CHECK_NULL);
 251 
 252   int len = JVMCIVMStructs::localHotSpotVMStructs_count();
 253   objArrayHandle vmFields = oopFactory::new_objArray(VMField::klass(), len, CHECK_NULL);
 254   for (int i = 0; i < len ; i++) {
 255     VMStructEntry vmField = JVMCIVMStructs::localHotSpotVMStructs[i];
 256     instanceHandle vmFieldObj = InstanceKlass::cast(VMField::klass())->allocate_instance_handle(CHECK_NULL);
 257     size_t name_buf_len = strlen(vmField.typeName) + strlen(vmField.fieldName) + 2 /* "::" */;
 258     char* name_buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, name_buf_len + 1);
 259     sprintf(name_buf, "%s::%s", vmField.typeName, vmField.fieldName);
 260     Handle name = java_lang_String::create_from_str(name_buf, CHECK_NULL);
 261     Handle type = java_lang_String::create_from_str(vmField.typeString, CHECK_NULL);
 262     VMField::set_name(vmFieldObj, name());
 263     VMField::set_type(vmFieldObj, type());
 264     VMField::set_offset(vmFieldObj, vmField.offset);
 265     VMField::set_address(vmFieldObj, (jlong) vmField.address);
 266     if (vmField.isStatic) {
 267       if (strcmp(vmField.typeString, "bool") == 0) {
 268         BOXED_LONG(value, *(jbyte*) vmField.address);
 269         VMField::set_value(vmFieldObj, value);
 270       } else if (strcmp(vmField.typeString, "int") == 0 ||
 271                  strcmp(vmField.typeString, "jint") == 0) {
 272         BOXED_LONG(value, *(jint*) vmField.address);
 273         VMField::set_value(vmFieldObj, value);
 274       } else if (strcmp(vmField.typeString, "uint64_t") == 0) {
 275         BOXED_LONG(value, *(uint64_t*) vmField.address);
 276         VMField::set_value(vmFieldObj, value);
 277       } else if (strcmp(vmField.typeString, "address") == 0 ||
 278                  strcmp(vmField.typeString, "intptr_t") == 0 ||
 279                  strcmp(vmField.typeString, "uintptr_t") == 0 ||
 280                  strcmp(vmField.typeString, "size_t") == 0 ||
 281                  // All foo* types are addresses.
 282                  vmField.typeString[strlen(vmField.typeString) - 1] == '*') {
 283         BOXED_LONG(value, *((address*) vmField.address));
 284         VMField::set_value(vmFieldObj, value);
 285       } else {
 286         JVMCI_ERROR_NULL("VM field %s has unsupported type %s", name_buf, vmField.typeString);
 287       }
 288     }
 289     vmFields->obj_at_put(i, vmFieldObj());
 290   }
 291 
 292   len = JVMCIVMStructs::localHotSpotVMTypes_count();
 293   objArrayHandle vmTypes = oopFactory::new_objArray(SystemDictionary::Object_klass(), len * 2, CHECK_NULL);
 294   for (int i = 0; i < len ; i++) {
 295     VMTypeEntry vmType = JVMCIVMStructs::localHotSpotVMTypes[i];
 296     Handle name = java_lang_String::create_from_str(vmType.typeName, CHECK_NULL);
 297     BOXED_LONG(size, vmType.size);
 298     vmTypes->obj_at_put(i * 2, name());
 299     vmTypes->obj_at_put(i * 2 + 1, size);
 300   }
 301 
 302   int ints_len = JVMCIVMStructs::localHotSpotVMIntConstants_count();
 303   int longs_len = JVMCIVMStructs::localHotSpotVMLongConstants_count();
 304   len = ints_len + longs_len;
 305   objArrayHandle vmConstants = oopFactory::new_objArray(SystemDictionary::Object_klass(), len * 2, CHECK_NULL);
 306   int insert = 0;
 307   for (int i = 0; i < ints_len ; i++) {
 308     VMIntConstantEntry c = JVMCIVMStructs::localHotSpotVMIntConstants[i];
 309     Handle name = java_lang_String::create_from_str(c.name, CHECK_NULL);
 310     BOXED_LONG(value, c.value);
 311     vmConstants->obj_at_put(insert++, name());
 312     vmConstants->obj_at_put(insert++, value);
 313   }
 314   for (int i = 0; i < longs_len ; i++) {
 315     VMLongConstantEntry c = JVMCIVMStructs::localHotSpotVMLongConstants[i];
 316     Handle name = java_lang_String::create_from_str(c.name, CHECK_NULL);
 317     BOXED_LONG(value, c.value);
 318     vmConstants->obj_at_put(insert++, name());
 319     vmConstants->obj_at_put(insert++, value);
 320   }
 321   assert(insert == len * 2, "must be");
 322 
 323   len = JVMCIVMStructs::localHotSpotVMAddresses_count();
 324   objArrayHandle vmAddresses = oopFactory::new_objArray(SystemDictionary::Object_klass(), len * 2, CHECK_NULL);
 325   for (int i = 0; i < len ; i++) {
 326     VMAddressEntry a = JVMCIVMStructs::localHotSpotVMAddresses[i];
 327     Handle name = java_lang_String::create_from_str(a.name, CHECK_NULL);
 328     BOXED_LONG(value, a.value);
 329     vmAddresses->obj_at_put(i * 2, name());
 330     vmAddresses->obj_at_put(i * 2 + 1, value);
 331   }
 332 
 333   // The last entry is the null entry.
 334   len = (int) Flag::numFlags - 1;
 335   objArrayHandle vmFlags = oopFactory::new_objArray(VMFlag::klass(), len, CHECK_NULL);
 336   for (int i = 0; i < len; i++) {
 337     Flag* flag = &Flag::flags[i];
 338     instanceHandle vmFlagObj = InstanceKlass::cast(VMFlag::klass())->allocate_instance_handle(CHECK_NULL);
 339     Handle name = java_lang_String::create_from_str(flag->_name, CHECK_NULL);
 340     Handle type = java_lang_String::create_from_str(flag->_type, CHECK_NULL);
 341     VMFlag::set_name(vmFlagObj, name());
 342     VMFlag::set_type(vmFlagObj, type());
 343     if (flag->is_bool()) {
 344       BOXED_LONG(value, flag->get_bool());
 345       VMFlag::set_value(vmFlagObj, value);
 346     } else if (flag->is_ccstr()) {
 347       Handle value = java_lang_String::create_from_str(flag->get_ccstr(), CHECK_NULL);
 348       VMFlag::set_value(vmFlagObj, value());
 349     } else if (flag->is_int()) {
 350       BOXED_LONG(value, flag->get_int());
 351       VMFlag::set_value(vmFlagObj, value);
 352     } else if (flag->is_intx()) {
 353       BOXED_LONG(value, flag->get_intx());
 354       VMFlag::set_value(vmFlagObj, value);
 355     } else if (flag->is_uint()) {
 356       BOXED_LONG(value, flag->get_uint());
 357       VMFlag::set_value(vmFlagObj, value);
 358     } else if (flag->is_uint64_t()) {
 359       BOXED_LONG(value, flag->get_uint64_t());
 360       VMFlag::set_value(vmFlagObj, value);
 361     } else if (flag->is_uintx()) {
 362       BOXED_LONG(value, flag->get_uintx());
 363       VMFlag::set_value(vmFlagObj, value);
 364     } else if (flag->is_double()) {
 365       BOXED_DOUBLE(value, flag->get_double());
 366       VMFlag::set_value(vmFlagObj, value);
 367     } else if (flag->is_size_t()) {
 368       BOXED_LONG(value, flag->get_size_t());
 369       VMFlag::set_value(vmFlagObj, value);
 370     } else {
 371       JVMCI_ERROR_NULL("VM flag %s has unsupported type %s", flag->_name, flag->_type);
 372     }
 373     vmFlags->obj_at_put(i, vmFlagObj());
 374   }
 375 
 376   objArrayHandle vmIntrinsics = CompilerToVM::initialize_intrinsics(CHECK_NULL);
 377 
 378   objArrayOop data = oopFactory::new_objArray(SystemDictionary::Object_klass(), 6, CHECK_NULL);
 379   data->obj_at_put(0, vmFields());
 380   data->obj_at_put(1, vmTypes());
 381   data->obj_at_put(2, vmConstants());
 382   data->obj_at_put(3, vmAddresses());
 383   data->obj_at_put(4, vmFlags());
 384   data->obj_at_put(5, vmIntrinsics());
 385 
 386   return (jobjectArray) JNIHandles::make_local(THREAD, data);
 387 #undef BOXED_LONG
 388 #undef BOXED_DOUBLE
 389 C2V_END
 390 
 391 C2V_VMENTRY(jbyteArray, getBytecode, (JNIEnv *, jobject, jobject jvmci_method))
 392   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 393   ResourceMark rm;
 394 
 395   int code_size = method->code_size();
 396   typeArrayOop reconstituted_code = oopFactory::new_byteArray(code_size, CHECK_NULL);
 397 
 398   guarantee(method->method_holder()->is_rewritten(), "Method's holder should be rewritten");
 399   // iterate over all bytecodes and replace non-Java bytecodes
 400 
 401   for (BytecodeStream s(method); s.next() != Bytecodes::_illegal; ) {
 402     Bytecodes::Code code = s.code();
 403     Bytecodes::Code raw_code = s.raw_code();
 404     int bci = s.bci();
 405     int len = s.instruction_size();
 406 
 407     // Restore original byte code.
 408     reconstituted_code->byte_at_put(bci, (jbyte) (s.is_wide()? Bytecodes::_wide : code));
 409     if (len > 1) {
 410       memcpy(reconstituted_code->byte_at_addr(bci + 1), s.bcp()+1, len-1);
 411     }
 412 
 413     if (len > 1) {
 414       // Restore the big-endian constant pool indexes.
 415       // Cf. Rewriter::scan_method
 416       switch (code) {
 417         case Bytecodes::_getstatic:
 418         case Bytecodes::_putstatic:
 419         case Bytecodes::_getfield:
 420         case Bytecodes::_putfield:
 421         case Bytecodes::_invokevirtual:
 422         case Bytecodes::_invokespecial:
 423         case Bytecodes::_invokestatic:
 424         case Bytecodes::_invokeinterface:
 425         case Bytecodes::_invokehandle: {
 426           int cp_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 427           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 428           break;
 429         }
 430 
 431         case Bytecodes::_invokedynamic:
 432           int cp_index = Bytes::get_native_u4((address) reconstituted_code->byte_at_addr(bci + 1));
 433           Bytes::put_Java_u4((address) reconstituted_code->byte_at_addr(bci + 1), (u4) cp_index);
 434           break;
 435       }
 436 
 437       // Not all ldc byte code are rewritten.
 438       switch (raw_code) {
 439         case Bytecodes::_fast_aldc: {
 440           int cpc_index = reconstituted_code->byte_at(bci + 1) & 0xff;
 441           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 442           assert(cp_index < method->constants()->length(), "sanity check");
 443           reconstituted_code->byte_at_put(bci + 1, (jbyte) cp_index);
 444           break;
 445         }
 446 
 447         case Bytecodes::_fast_aldc_w: {
 448           int cpc_index = Bytes::get_native_u2((address) reconstituted_code->byte_at_addr(bci + 1));
 449           int cp_index = method->constants()->object_to_cp_index(cpc_index);
 450           assert(cp_index < method->constants()->length(), "sanity check");
 451           Bytes::put_Java_u2((address) reconstituted_code->byte_at_addr(bci + 1), (u2) cp_index);
 452           break;
 453         }
 454       }
 455     }
 456   }
 457 
 458   return (jbyteArray) JNIHandles::make_local(THREAD, reconstituted_code);
 459 C2V_END
 460 
 461 C2V_VMENTRY(jint, getExceptionTableLength, (JNIEnv *, jobject, jobject jvmci_method))
 462   ResourceMark rm;
 463   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 464   return method->exception_table_length();
 465 C2V_END
 466 
 467 C2V_VMENTRY(jlong, getExceptionTableStart, (JNIEnv *, jobject, jobject jvmci_method))
 468   ResourceMark rm;
 469   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 470   if (method->exception_table_length() == 0) {
 471     return 0L;
 472   }
 473   return (jlong) (address) method->exception_table_start();
 474 C2V_END
 475 
 476 C2V_VMENTRY(jobject, asResolvedJavaMethod, (JNIEnv *, jobject, jobject executable_handle))
 477   oop executable = JNIHandles::resolve(executable_handle);
 478   oop mirror = NULL;
 479   int slot = 0;
 480 
 481   if (executable->klass() == SystemDictionary::reflect_Constructor_klass()) {
 482     mirror = java_lang_reflect_Constructor::clazz(executable);
 483     slot = java_lang_reflect_Constructor::slot(executable);
 484   } else {
 485     assert(executable->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
 486     mirror = java_lang_reflect_Method::clazz(executable);
 487     slot = java_lang_reflect_Method::slot(executable);
 488   }
 489   Klass* holder = java_lang_Class::as_Klass(mirror);
 490   methodHandle method = InstanceKlass::cast(holder)->method_with_idnum(slot);
 491   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 492   return JNIHandles::make_local(THREAD, result);
 493 }
 494 
 495 C2V_VMENTRY(jobject, getResolvedJavaMethod, (JNIEnv *, jobject, jobject base, jlong offset))
 496   methodHandle method;
 497   oop base_object = JNIHandles::resolve(base);
 498   if (base_object == NULL) {
 499     method = *((Method**)(offset));
 500   } else if (base_object->is_a(SystemDictionary::MemberName_klass())) {
 501     method = (Method*) (intptr_t) base_object->long_field(offset);
 502   } else if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 503     method = *((Method**)(HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object) + offset));
 504   } else {
 505     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 506                 err_msg("Unexpected type: %s", base_object->klass()->external_name()));
 507   }
 508   assert (method.is_null() || method->is_method(), "invalid read");
 509   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 510   return JNIHandles::make_local(THREAD, result);
 511 }
 512 
 513 C2V_VMENTRY(jobject, getConstantPool, (JNIEnv *, jobject, jobject object_handle))
 514   constantPoolHandle cp;
 515   oop object = JNIHandles::resolve(object_handle);
 516   if (object == NULL) {
 517     THROW_0(vmSymbols::java_lang_NullPointerException());
 518   }
 519   if (object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 520     cp = CompilerToVM::asMethod(object)->constMethod()->constants();
 521   } else if (object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 522     cp = InstanceKlass::cast(CompilerToVM::asKlass(object))->constants();
 523   } else {
 524     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 525                 err_msg("Unexpected type: %s", object->klass()->external_name()));
 526   }
 527   assert(!cp.is_null(), "npe");
 528   JavaValue method_result(T_OBJECT);
 529   JavaCallArguments args;
 530   args.push_long((jlong) (address) cp());
 531   JavaCalls::call_static(&method_result, SystemDictionary::HotSpotConstantPool_klass(), vmSymbols::fromMetaspace_name(), vmSymbols::constantPool_fromMetaspace_signature(), &args, CHECK_NULL);
 532   return JNIHandles::make_local(THREAD, (oop)method_result.get_jobject());
 533 }
 534 
 535 C2V_VMENTRY(jobject, getResolvedJavaType, (JNIEnv *, jobject, jobject base, jlong offset, jboolean compressed))
 536   KlassHandle klass;
 537   oop base_object = JNIHandles::resolve(base);
 538   jlong base_address = 0;
 539   if (base_object != NULL && offset == oopDesc::klass_offset_in_bytes()) {
 540     klass = base_object->klass();
 541   } else if (!compressed) {
 542     if (base_object != NULL) {
 543       if (base_object->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 544         base_address = HotSpotResolvedJavaMethodImpl::metaspaceMethod(base_object);
 545       } else if (base_object->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 546         base_address = HotSpotConstantPool::metaspaceConstantPool(base_object);
 547       } else if (base_object->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 548         base_address = (jlong) CompilerToVM::asKlass(base_object);
 549       } else if (base_object->is_a(SystemDictionary::Class_klass())) {
 550         base_address = (jlong) (address) base_object;
 551       } else {
 552         THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 553                     err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", base_object->klass()->external_name(), offset, compressed ? "true" : "false"));
 554       }
 555     }
 556     klass = *((Klass**) (intptr_t) (base_address + offset));
 557   } else {
 558     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 559                 err_msg("Unexpected arguments: %s " JLONG_FORMAT " %s", base_object->klass()->external_name(), offset, compressed ? "true" : "false"));
 560   }
 561   assert (klass.is_null() || klass->is_klass(), "invalid read");
 562   oop result = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 563   return JNIHandles::make_local(THREAD, result);
 564 }
 565 
 566 C2V_VMENTRY(jobject, findUniqueConcreteMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 567   ResourceMark rm;
 568   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 569   KlassHandle holder = CompilerToVM::asKlass(jvmci_type);
 570   if (holder->is_interface()) {
 571     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", holder->external_name()));
 572   }
 573 
 574   methodHandle ucm;
 575   {
 576     MutexLocker locker(Compile_lock);
 577     ucm = Dependencies::find_unique_concrete_method(holder(), method());
 578   }
 579   oop result = CompilerToVM::get_jvmci_method(ucm, CHECK_NULL);
 580   return JNIHandles::make_local(THREAD, result);
 581 C2V_END
 582 
 583 C2V_VMENTRY(jobject, getImplementor, (JNIEnv *, jobject, jobject jvmci_type))
 584   InstanceKlass* klass = (InstanceKlass*) CompilerToVM::asKlass(jvmci_type);
 585   oop implementor = CompilerToVM::get_jvmci_type(klass->implementor(), CHECK_NULL);
 586   return JNIHandles::make_local(THREAD, implementor);
 587 C2V_END
 588 
 589 C2V_VMENTRY(jboolean, methodIsIgnoredBySecurityStackWalk,(JNIEnv *, jobject, jobject jvmci_method))
 590   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 591   return method->is_ignored_by_security_stack_walk();
 592 C2V_END
 593 
 594 C2V_VMENTRY(jboolean, canInlineMethod,(JNIEnv *, jobject, jobject jvmci_method))
 595   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 596   // In hosted mode ignore the not_compilable flags since they are never set by
 597   // the JVMCI compiler.
 598   bool is_compilable = UseJVMCICompiler ? !method->is_not_compilable(CompLevel_full_optimization) : true;
 599   return is_compilable && !CompilerOracle::should_not_inline(method) && !method->dont_inline();
 600 C2V_END
 601 
 602 C2V_VMENTRY(jboolean, shouldInlineMethod,(JNIEnv *, jobject, jobject jvmci_method))
 603   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 604   return CompilerOracle::should_inline(method) || method->force_inline();
 605 C2V_END
 606 
 607 C2V_VMENTRY(jobject, lookupType, (JNIEnv*, jobject, jstring jname, jclass accessing_class, jboolean resolve))
 608   ResourceMark rm;
 609   Handle name = JNIHandles::resolve(jname);
 610   Symbol* class_name = java_lang_String::as_symbol(name, CHECK_0);
 611   if (java_lang_String::length(name()) <= 1) {
 612     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Primitive type %s should be handled in Java code", class_name->as_C_string()));
 613   }
 614 
 615   Klass* resolved_klass = NULL;
 616   Handle class_loader;
 617   Handle protection_domain;
 618   if (JNIHandles::resolve(accessing_class) == NULL) {
 619     THROW_0(vmSymbols::java_lang_NullPointerException());
 620   }
 621   Klass* accessing_klass = java_lang_Class::as_Klass(JNIHandles::resolve(accessing_class));
 622   class_loader = accessing_klass->class_loader();
 623   protection_domain = accessing_klass->protection_domain();
 624 
 625   if (resolve) {
 626     resolved_klass = SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK_0);
 627   } else {
 628     if (class_name->byte_at(0) == 'L' &&
 629       class_name->byte_at(class_name->utf8_length()-1) == ';') {
 630       // This is a name from a signature.  Strip off the trimmings.
 631       // Call recursive to keep scope of strippedsym.
 632       TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1,
 633                                                           class_name->utf8_length()-2,
 634                                                           CHECK_0);
 635       resolved_klass = SystemDictionary::find(strippedsym, class_loader, protection_domain, CHECK_0);
 636     } else if (FieldType::is_array(class_name)) {
 637       FieldArrayInfo fd;
 638       // dimension and object_key in FieldArrayInfo are assigned as a side-effect
 639       // of this call
 640       BasicType t = FieldType::get_array_info(class_name, fd, CHECK_0);
 641       if (t == T_OBJECT) {
 642         TempNewSymbol strippedsym = SymbolTable::new_symbol(class_name->as_utf8()+1+fd.dimension(),
 643                                                             class_name->utf8_length()-2-fd.dimension(),
 644                                                             CHECK_0);
 645         // naked oop "k" is OK here -- we assign back into it
 646         resolved_klass = SystemDictionary::find(strippedsym,
 647                                                              class_loader,
 648                                                              protection_domain,
 649                                                              CHECK_0);
 650         if (resolved_klass != NULL) {
 651           resolved_klass = resolved_klass->array_klass(fd.dimension(), CHECK_0);
 652         }
 653       } else {
 654         resolved_klass = Universe::typeArrayKlassObj(t);
 655         resolved_klass = TypeArrayKlass::cast(resolved_klass)->array_klass(fd.dimension(), CHECK_0);
 656       }
 657     }
 658   }
 659   Handle result = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 660   return JNIHandles::make_local(THREAD, result());
 661 C2V_END
 662 
 663 C2V_VMENTRY(jobject, resolveConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 664   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 665   oop result = cp->resolve_constant_at(index, CHECK_NULL);
 666   return JNIHandles::make_local(THREAD, result);
 667 C2V_END
 668 
 669 C2V_VMENTRY(jobject, resolvePossiblyCachedConstantInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 670   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 671   oop result = cp->resolve_possibly_cached_constant_at(index, CHECK_NULL);
 672   return JNIHandles::make_local(THREAD, result);
 673 C2V_END
 674 
 675 C2V_VMENTRY(jint, lookupNameAndTypeRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 676   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 677   return cp->name_and_type_ref_index_at(index);
 678 C2V_END
 679 
 680 C2V_VMENTRY(jobject, lookupNameInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 681   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 682   Handle sym = java_lang_String::create_from_symbol(cp->name_ref_at(which), CHECK_NULL);
 683   return JNIHandles::make_local(THREAD, sym());
 684 C2V_END
 685 
 686 C2V_VMENTRY(jobject, lookupSignatureInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint which))
 687   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 688   Handle sym = java_lang_String::create_from_symbol(cp->signature_ref_at(which), CHECK_NULL);
 689   return JNIHandles::make_local(THREAD, sym());
 690 C2V_END
 691 
 692 C2V_VMENTRY(jint, lookupKlassRefIndexInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 693   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 694   return cp->klass_ref_index_at(index);
 695 C2V_END
 696 
 697 C2V_VMENTRY(jobject, resolveTypeInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 698   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 699   Klass* resolved_klass = cp->klass_at(index, CHECK_NULL);
 700   Handle klass = CompilerToVM::get_jvmci_type(resolved_klass, CHECK_NULL);
 701   return JNIHandles::make_local(THREAD, klass());
 702 C2V_END
 703 
 704 C2V_VMENTRY(jobject, lookupKlassInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 705   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 706   KlassHandle loading_klass(cp->pool_holder());
 707   bool is_accessible = false;
 708   KlassHandle klass = JVMCIEnv::get_klass_by_index(cp, index, is_accessible, loading_klass);
 709   Symbol* symbol = NULL;
 710   if (klass.is_null()) {
 711     symbol = cp->klass_name_at(index);
 712   }
 713   Handle result;
 714   if (!klass.is_null()) {
 715     result = CompilerToVM::get_jvmci_type(klass, CHECK_NULL);
 716   } else {
 717     result = java_lang_String::create_from_symbol(symbol, CHECK_NULL);
 718   }
 719   return JNIHandles::make_local(THREAD, result());
 720 C2V_END
 721 
 722 C2V_VMENTRY(jobject, lookupAppendixInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 723   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 724   oop appendix_oop = ConstantPool::appendix_at_if_loaded(cp, index);
 725   return JNIHandles::make_local(THREAD, appendix_oop);
 726 C2V_END
 727 
 728 C2V_VMENTRY(jobject, lookupMethodInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jbyte opcode))
 729   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 730   instanceKlassHandle pool_holder(cp->pool_holder());
 731   Bytecodes::Code bc = (Bytecodes::Code) (((int) opcode) & 0xFF);
 732   methodHandle method = JVMCIEnv::get_method_by_index(cp, index, bc, pool_holder);
 733   oop result = CompilerToVM::get_jvmci_method(method, CHECK_NULL);
 734   return JNIHandles::make_local(THREAD, result);
 735 C2V_END
 736 
 737 C2V_VMENTRY(jint, constantPoolRemapInstructionOperandFromCache, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
 738   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 739   return cp->remap_instruction_operand_from_cache(index);
 740 C2V_END
 741 
 742 C2V_VMENTRY(jobject, resolveFieldInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index, jobject jvmci_method, jbyte opcode, jlongArray info_handle))
 743   ResourceMark rm;
 744   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
 745   Bytecodes::Code code = (Bytecodes::Code)(((int) opcode) & 0xFF);
 746   fieldDescriptor fd;
 747   LinkInfo link_info(cp, index, (jvmci_method != NULL) ? CompilerToVM::asMethod(jvmci_method) : NULL, CHECK_0);
 748   LinkResolver::resolve_field(fd, link_info, Bytecodes::java_code(code), false, CHECK_0);
 749   typeArrayOop info = (typeArrayOop) JNIHandles::resolve(info_handle);
 750   assert(info != NULL && info->length() == 2, "must be");
 751   info->long_at_put(0, (jlong) fd.access_flags().as_int());
 752   info->long_at_put(1, (jlong) fd.offset());
 753   oop field_holder = CompilerToVM::get_jvmci_type(fd.field_holder(), CHECK_NULL);
 754   return JNIHandles::make_local(THREAD, field_holder);
 755 C2V_END
 756 
 757 C2V_VMENTRY(jint, getVtableIndexForInterfaceMethod, (JNIEnv *, jobject, jobject jvmci_type, jobject jvmci_method))
 758   ResourceMark rm;
 759   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 760   Method* method = CompilerToVM::asMethod(jvmci_method);
 761   if (klass->is_interface()) {
 762     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Interface %s should be handled in Java code", klass->external_name()));
 763   }
 764   if (!method->method_holder()->is_interface()) {
 765     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()));
 766   }
 767   if (!InstanceKlass::cast(klass)->is_linked()) {
 768     THROW_MSG_0(vmSymbols::java_lang_InternalError(), err_msg("Class %s must be linked", klass->external_name()));
 769   }
 770   return LinkResolver::vtable_index_of_interface_method(klass, method);
 771 C2V_END
 772 
 773 C2V_VMENTRY(jobject, resolveMethod, (JNIEnv *, jobject, jobject receiver_jvmci_type, jobject jvmci_method, jobject caller_jvmci_type))
 774   KlassHandle recv_klass = CompilerToVM::asKlass(receiver_jvmci_type);
 775   KlassHandle caller_klass = CompilerToVM::asKlass(caller_jvmci_type);
 776   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 777 
 778   KlassHandle h_resolved   (THREAD, method->method_holder());
 779   Symbol* h_name      = method->name();
 780   Symbol* h_signature = method->signature();
 781 
 782   if (MethodHandles::is_signature_polymorphic_method(method())) {
 783       // Signature polymorphic methods are already resolved, JVMCI just returns NULL in this case.
 784       return NULL;
 785   }
 786 
 787   LinkInfo link_info(h_resolved, h_name, h_signature, caller_klass);
 788   methodHandle m;
 789   // Only do exact lookup if receiver klass has been linked.  Otherwise,
 790   // the vtable has not been setup, and the LinkResolver will fail.
 791   if (recv_klass->is_array_klass() ||
 792       InstanceKlass::cast(recv_klass())->is_linked() && !recv_klass->is_interface()) {
 793     if (h_resolved->is_interface()) {
 794       m = LinkResolver::resolve_interface_call_or_null(recv_klass, link_info);
 795     } else {
 796       m = LinkResolver::resolve_virtual_call_or_null(recv_klass, link_info);
 797     }
 798   }
 799 
 800   if (m.is_null()) {
 801     // Return NULL if there was a problem with lookup (uninitialized class, etc.)
 802     return NULL;
 803   }
 804 
 805   oop result = CompilerToVM::get_jvmci_method(m, CHECK_NULL);
 806   return JNIHandles::make_local(THREAD, result);
 807 C2V_END
 808 
 809 C2V_VMENTRY(jboolean, hasFinalizableSubclass,(JNIEnv *, jobject, jobject jvmci_type))
 810   Klass* klass = CompilerToVM::asKlass(jvmci_type);
 811   assert(klass != NULL, "method must not be called for primitive types");
 812   return Dependencies::find_finalizable_subclass(klass) != NULL;
 813 C2V_END
 814 
 815 C2V_VMENTRY(jobject, getClassInitializer, (JNIEnv *, jobject, jobject jvmci_type))
 816   InstanceKlass* klass = (InstanceKlass*) CompilerToVM::asKlass(jvmci_type);
 817   oop result = CompilerToVM::get_jvmci_method(klass->class_initializer(), CHECK_NULL);
 818   return JNIHandles::make_local(THREAD, result);
 819 C2V_END
 820 
 821 C2V_VMENTRY(jlong, getMaxCallTargetOffset, (JNIEnv*, jobject, jlong addr))
 822   address target_addr = (address) addr;
 823   if (target_addr != 0x0) {
 824     int64_t off_low = (int64_t)target_addr - ((int64_t)CodeCache::low_bound() + sizeof(int));
 825     int64_t off_high = (int64_t)target_addr - ((int64_t)CodeCache::high_bound() + sizeof(int));
 826     return MAX2(ABS(off_low), ABS(off_high));
 827   }
 828   return -1;
 829 C2V_END
 830 
 831 C2V_VMENTRY(void, doNotInlineOrCompile,(JNIEnv *, jobject,  jobject jvmci_method))
 832   methodHandle method = CompilerToVM::asMethod(jvmci_method);
 833   method->set_not_c1_compilable();
 834   method->set_not_c2_compilable();
 835   method->set_dont_inline(true);
 836 C2V_END
 837 
 838 C2V_VMENTRY(jint, installCode, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject installed_code, jobject speculation_log))
 839   ResourceMark rm;
 840   HandleMark hm;
 841   Handle target_handle = JNIHandles::resolve(target);
 842   Handle compiled_code_handle = JNIHandles::resolve(compiled_code);
 843   CodeBlob* cb = NULL;
 844   Handle installed_code_handle = JNIHandles::resolve(installed_code);
 845   Handle speculation_log_handle = JNIHandles::resolve(speculation_log);
 846 
 847   JVMCICompiler* compiler = JVMCICompiler::instance(CHECK_JNI_ERR);
 848 
 849   TraceTime install_time("installCode", JVMCICompiler::codeInstallTimer());
 850   bool is_immutable_PIC = HotSpotCompiledCode::isImmutablePIC(compiled_code_handle) > 0;
 851   CodeInstaller installer(is_immutable_PIC);
 852   JVMCIEnv::CodeInstallResult result = installer.install(compiler, target_handle, compiled_code_handle, cb, installed_code_handle, speculation_log_handle, CHECK_0);
 853 
 854   if (PrintCodeCacheOnCompilation) {
 855     stringStream s;
 856     // Dump code cache  into a buffer before locking the tty,
 857     {
 858       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 859       CodeCache::print_summary(&s, false);
 860     }
 861     ttyLocker ttyl;
 862     tty->print_raw_cr(s.as_string());
 863   }
 864 
 865   if (result != JVMCIEnv::ok) {
 866     assert(cb == NULL, "should be");
 867   } else {
 868     if (!installed_code_handle.is_null()) {
 869       assert(installed_code_handle->is_a(InstalledCode::klass()), "wrong type");
 870       nmethod::invalidate_installed_code(installed_code_handle, CHECK_0);
 871       {
 872         // Ensure that all updates to the InstalledCode fields are consistent.
 873         MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 874         InstalledCode::set_address(installed_code_handle, (jlong) cb);
 875         InstalledCode::set_version(installed_code_handle, InstalledCode::version(installed_code_handle) + 1);
 876         if (cb->is_nmethod()) {
 877           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->as_nmethod_or_null()->verified_entry_point());
 878         } else {
 879           InstalledCode::set_entryPoint(installed_code_handle, (jlong) cb->code_begin());
 880         }
 881         if (installed_code_handle->is_a(HotSpotInstalledCode::klass())) {
 882           HotSpotInstalledCode::set_size(installed_code_handle, cb->size());
 883           HotSpotInstalledCode::set_codeStart(installed_code_handle, (jlong) cb->code_begin());
 884           HotSpotInstalledCode::set_codeSize(installed_code_handle, cb->code_size());
 885         }
 886       }
 887       nmethod* nm = cb->as_nmethod_or_null();
 888       if (nm != NULL && installed_code_handle->is_scavengable()) {
 889         assert(nm->detect_scavenge_root_oops(), "nm should be scavengable if installed_code is scavengable");
 890         if (!UseG1GC) {
 891           assert(nm->on_scavenge_root_list(), "nm should be on scavengable list");
 892         }
 893       }
 894     }
 895   }
 896   return result;
 897 C2V_END
 898 
 899 C2V_VMENTRY(jint, getMetadata, (JNIEnv *jniEnv, jobject, jobject target, jobject compiled_code, jobject metadata))
 900   ResourceMark rm;
 901   HandleMark hm;
 902 
 903   Handle target_handle = JNIHandles::resolve(target);
 904   Handle compiled_code_handle = JNIHandles::resolve(compiled_code);
 905   Handle metadata_handle = JNIHandles::resolve(metadata);
 906 
 907   CodeMetadata code_metadata;
 908   CodeBlob *cb = NULL;
 909   CodeInstaller installer(true /* immutable PIC compilation */);
 910 
 911   JVMCIEnv::CodeInstallResult result = installer.gather_metadata(target_handle, compiled_code_handle, code_metadata, CHECK_0);
 912   if (result != JVMCIEnv::ok) {
 913     return result;
 914   }
 915 
 916   if (code_metadata.get_nr_pc_desc() > 0) {
 917     typeArrayHandle pcArrayOop = oopFactory::new_byteArray(sizeof(PcDesc) * code_metadata.get_nr_pc_desc(), CHECK_(JVMCIEnv::cache_full));
 918     memcpy(pcArrayOop->byte_at_addr(0), code_metadata.get_pc_desc(), sizeof(PcDesc) * code_metadata.get_nr_pc_desc());
 919     HotSpotMetaData::set_pcDescBytes(metadata_handle, pcArrayOop());
 920   }
 921 
 922   if (code_metadata.get_scopes_size() > 0) {
 923     typeArrayHandle scopesArrayOop = oopFactory::new_byteArray(code_metadata.get_scopes_size(), CHECK_(JVMCIEnv::cache_full));
 924     memcpy(scopesArrayOop->byte_at_addr(0), code_metadata.get_scopes_desc(), code_metadata.get_scopes_size());
 925     HotSpotMetaData::set_scopesDescBytes(metadata_handle, scopesArrayOop());
 926   }
 927 
 928   RelocBuffer* reloc_buffer = code_metadata.get_reloc_buffer();
 929   typeArrayHandle relocArrayOop = oopFactory::new_byteArray((int) reloc_buffer->size(), CHECK_(JVMCIEnv::cache_full));
 930   if (reloc_buffer->size() > 0) {
 931     memcpy(relocArrayOop->byte_at_addr(0), reloc_buffer->begin(), reloc_buffer->size());
 932   }
 933   HotSpotMetaData::set_relocBytes(metadata_handle, relocArrayOop());
 934 
 935   const OopMapSet* oopMapSet = installer.oopMapSet();
 936   {
 937     ResourceMark mark;
 938     ImmutableOopMapBuilder builder(oopMapSet);
 939     int oopmap_size = builder.heap_size();
 940     typeArrayHandle oopMapArrayHandle = oopFactory::new_byteArray(oopmap_size, CHECK_(JVMCIEnv::cache_full));
 941     builder.generate_into((address) oopMapArrayHandle->byte_at_addr(0));
 942     HotSpotMetaData::set_oopMaps(metadata_handle, oopMapArrayHandle());
 943   }
 944 
 945   AOTOopRecorder* recorder = code_metadata.get_oop_recorder();
 946 
 947   int nr_meta_strings = recorder->nr_meta_strings();
 948   objArrayHandle metadataArrayHandle = oopFactory::new_objectArray(nr_meta_strings, CHECK_(JVMCIEnv::cache_full));
 949   for (int i = 0; i < nr_meta_strings; ++i) {
 950     const char* element = recorder->meta_element(i);
 951     Handle java_string = java_lang_String::create_from_str(element, CHECK_(JVMCIEnv::cache_full));
 952     metadataArrayHandle->obj_at_put(i, java_string());
 953   }
 954   HotSpotMetaData::set_metadata(metadata_handle, metadataArrayHandle());
 955 
 956   ExceptionHandlerTable* handler = code_metadata.get_exception_table();
 957   int table_size = handler->size_in_bytes();
 958   typeArrayHandle exceptionArrayOop = oopFactory::new_byteArray(table_size, CHECK_(JVMCIEnv::cache_full));
 959 
 960   if (table_size > 0) {
 961     handler->copy_bytes_to((address) exceptionArrayOop->byte_at_addr(0));
 962   }
 963   HotSpotMetaData::set_exceptionBytes(metadata_handle, exceptionArrayOop());
 964 
 965   return result;
 966 C2V_END
 967 
 968 C2V_VMENTRY(void, resetCompilationStatistics, (JNIEnv *jniEnv, jobject))
 969   JVMCICompiler* compiler = JVMCICompiler::instance(CHECK);
 970   CompilerStatistics* stats = compiler->stats();
 971   stats->_standard.reset();
 972   stats->_osr.reset();
 973 C2V_END
 974 
 975 C2V_VMENTRY(jobject, disassembleCodeBlob, (JNIEnv *jniEnv, jobject, jobject installedCode))
 976   ResourceMark rm;
 977   HandleMark hm;
 978 
 979   if (installedCode == NULL) {
 980     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), "installedCode is null");
 981   }
 982 
 983   jlong codeBlob = InstalledCode::address(installedCode);
 984   if (codeBlob == 0L) {
 985     return NULL;
 986   }
 987 
 988   CodeBlob* cb = (CodeBlob*) (address) codeBlob;
 989   if (cb == NULL) {
 990     return NULL;
 991   }
 992 
 993   // We don't want the stringStream buffer to resize during disassembly as it
 994   // uses scoped resource memory. If a nested function called during disassembly uses
 995   // a ResourceMark and the buffer expands within the scope of the mark,
 996   // the buffer becomes garbage when that scope is exited. Experience shows that
 997   // the disassembled code is typically about 10x the code size so a fixed buffer
 998   // sized to 20x code size plus a fixed amount for header info should be sufficient.
 999   int bufferSize = cb->code_size() * 20 + 1024;
1000   char* buffer = NEW_RESOURCE_ARRAY(char, bufferSize);
1001   stringStream st(buffer, bufferSize);
1002   if (cb->is_nmethod()) {
1003     nmethod* nm = (nmethod*) cb;
1004     if (!nm->is_alive()) {
1005       return NULL;
1006     }
1007   }
1008   Disassembler::decode(cb, &st);
1009   if (st.size() <= 0) {
1010     return NULL;
1011   }
1012 
1013   Handle result = java_lang_String::create_from_platform_dependent_str(st.as_string(), CHECK_NULL);
1014   return JNIHandles::make_local(THREAD, result());
1015 C2V_END
1016 
1017 C2V_VMENTRY(jobject, getStackTraceElement, (JNIEnv*, jobject, jobject jvmci_method, int bci))
1018   ResourceMark rm;
1019   HandleMark hm;
1020 
1021   methodHandle method = CompilerToVM::asMethod(jvmci_method);
1022   oop element = java_lang_StackTraceElement::create(method, bci, CHECK_NULL);
1023   return JNIHandles::make_local(THREAD, element);
1024 C2V_END
1025 
1026 C2V_VMENTRY(jobject, executeInstalledCode, (JNIEnv*, jobject, jobject args, jobject hotspotInstalledCode))
1027   ResourceMark rm;
1028   HandleMark hm;
1029 
1030   jlong nmethodValue = InstalledCode::address(hotspotInstalledCode);
1031   if (nmethodValue == 0L) {
1032     THROW_NULL(vmSymbols::jdk_vm_ci_code_InvalidInstalledCodeException());
1033   }
1034   nmethod* nm = (nmethod*) (address) nmethodValue;
1035   methodHandle mh = nm->method();
1036   Symbol* signature = mh->signature();
1037   JavaCallArguments jca(mh->size_of_parameters());
1038 
1039   JavaArgumentUnboxer jap(signature, &jca, (arrayOop) JNIHandles::resolve(args), mh->is_static());
1040   JavaValue result(jap.get_ret_type());
1041   jca.set_alternative_target(nm);
1042   JavaCalls::call(&result, mh, &jca, CHECK_NULL);
1043 
1044   if (jap.get_ret_type() == T_VOID) {
1045     return NULL;
1046   } else if (jap.get_ret_type() == T_OBJECT || jap.get_ret_type() == T_ARRAY) {
1047     return JNIHandles::make_local(THREAD, (oop) result.get_jobject());
1048   } else {
1049     jvalue *value = (jvalue *) result.get_value_addr();
1050     // Narrow the value down if required (Important on big endian machines)
1051     switch (jap.get_ret_type()) {
1052       case T_BOOLEAN:
1053        value->z = (jboolean) value->i;
1054        break;
1055       case T_BYTE:
1056        value->b = (jbyte) value->i;
1057        break;
1058       case T_CHAR:
1059        value->c = (jchar) value->i;
1060        break;
1061       case T_SHORT:
1062        value->s = (jshort) value->i;
1063        break;
1064      }
1065     oop o = java_lang_boxing_object::create(jap.get_ret_type(), value, CHECK_NULL);
1066     return JNIHandles::make_local(THREAD, o);
1067   }
1068 C2V_END
1069 
1070 C2V_VMENTRY(jlongArray, getLineNumberTable, (JNIEnv *, jobject, jobject jvmci_method))
1071   Method* method = CompilerToVM::asMethod(jvmci_method);
1072   if (!method->has_linenumber_table()) {
1073     return NULL;
1074   }
1075   u2 num_entries = 0;
1076   CompressedLineNumberReadStream streamForSize(method->compressed_linenumber_table());
1077   while (streamForSize.read_pair()) {
1078     num_entries++;
1079   }
1080 
1081   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
1082   typeArrayOop result = oopFactory::new_longArray(2 * num_entries, CHECK_NULL);
1083 
1084   int i = 0;
1085   jlong value;
1086   while (stream.read_pair()) {
1087     value = ((long) stream.bci());
1088     result->long_at_put(i, value);
1089     value = ((long) stream.line());
1090     result->long_at_put(i + 1, value);
1091     i += 2;
1092   }
1093 
1094   return (jlongArray) JNIHandles::make_local(THREAD, result);
1095 C2V_END
1096 
1097 C2V_VMENTRY(jlong, getLocalVariableTableStart, (JNIEnv *, jobject, jobject jvmci_method))
1098   ResourceMark rm;
1099   Method* method = CompilerToVM::asMethod(jvmci_method);
1100   if (!method->has_localvariable_table()) {
1101     return 0;
1102   }
1103   return (jlong) (address) method->localvariable_table_start();
1104 C2V_END
1105 
1106 C2V_VMENTRY(jint, getLocalVariableTableLength, (JNIEnv *, jobject, jobject jvmci_method))
1107   ResourceMark rm;
1108   Method* method = CompilerToVM::asMethod(jvmci_method);
1109   return method->localvariable_table_length();
1110 C2V_END
1111 
1112 C2V_VMENTRY(void, reprofile, (JNIEnv*, jobject, jobject jvmci_method))
1113   Method* method = CompilerToVM::asMethod(jvmci_method);
1114   MethodCounters* mcs = method->method_counters();
1115   if (mcs != NULL) {
1116     mcs->clear_counters();
1117   }
1118   NOT_PRODUCT(method->set_compiled_invocation_count(0));
1119 
1120   CompiledMethod* code = method->code();
1121   if (code != NULL) {
1122     code->make_not_entrant();
1123   }
1124 
1125   MethodData* method_data = method->method_data();
1126   if (method_data == NULL) {
1127     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
1128     method_data = MethodData::allocate(loader_data, method, CHECK);
1129     method->set_method_data(method_data);
1130   } else {
1131     method_data->initialize();
1132   }
1133 C2V_END
1134 
1135 
1136 C2V_VMENTRY(void, invalidateInstalledCode, (JNIEnv*, jobject, jobject installed_code))
1137   Handle installed_code_handle = JNIHandles::resolve(installed_code);
1138   nmethod::invalidate_installed_code(installed_code_handle, CHECK);
1139 C2V_END
1140 
1141 C2V_VMENTRY(jlongArray, collectCounters, (JNIEnv*, jobject))
1142   typeArrayOop arrayOop = oopFactory::new_longArray(JVMCICounterSize, CHECK_NULL);
1143   JavaThread::collect_counters(arrayOop);
1144   return (jlongArray) JNIHandles::make_local(THREAD, arrayOop);
1145 C2V_END
1146 
1147 C2V_VMENTRY(int, allocateCompileId, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci))
1148   HandleMark hm;
1149   ResourceMark rm;
1150   if (JNIHandles::resolve(jvmci_method) == NULL) {
1151     THROW_0(vmSymbols::java_lang_NullPointerException());
1152   }
1153   Method* method = CompilerToVM::asMethod(jvmci_method);
1154   if (entry_bci >= method->code_size() || entry_bci < -1) {
1155     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Unexpected bci %d", entry_bci));
1156   }
1157   return CompileBroker::assign_compile_id_unlocked(THREAD, method, entry_bci);
1158 C2V_END
1159 
1160 
1161 C2V_VMENTRY(jboolean, isMature, (JNIEnv*, jobject, jlong metaspace_method_data))
1162   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
1163   return mdo != NULL && mdo->is_mature();
1164 C2V_END
1165 
1166 C2V_VMENTRY(jboolean, hasCompiledCodeForOSR, (JNIEnv*, jobject, jobject jvmci_method, int entry_bci, int comp_level))
1167   Method* method = CompilerToVM::asMethod(jvmci_method);
1168   return method->lookup_osr_nmethod_for(entry_bci, comp_level, true) != NULL;
1169 C2V_END
1170 
1171 C2V_VMENTRY(jobject, getSymbol, (JNIEnv*, jobject, jlong symbol))
1172   Handle sym = java_lang_String::create_from_symbol((Symbol*)(address)symbol, CHECK_NULL);
1173   return JNIHandles::make_local(THREAD, sym());
1174 C2V_END
1175 
1176 bool matches(jobjectArray methods, Method* method) {
1177   objArrayOop methods_oop = (objArrayOop) JNIHandles::resolve(methods);
1178 
1179   for (int i = 0; i < methods_oop->length(); i++) {
1180     oop resolved = methods_oop->obj_at(i);
1181     if (resolved->is_a(HotSpotResolvedJavaMethodImpl::klass()) && CompilerToVM::asMethod(resolved) == method) {
1182       return true;
1183     }
1184   }
1185   return false;
1186 }
1187 
1188 C2V_VMENTRY(jobject, getNextStackFrame, (JNIEnv*, jobject compilerToVM, jobject hs_frame, jobjectArray methods, jint initialSkip))
1189   ResourceMark rm;
1190 
1191   if (!thread->has_last_Java_frame()) return NULL;
1192   Handle result = HotSpotStackFrameReference::klass()->allocate_instance(thread);
1193   HotSpotStackFrameReference::klass()->initialize(thread);
1194 
1195   StackFrameStream fst(thread);
1196   if (hs_frame != NULL) {
1197     // look for the correct stack frame if one is given
1198     intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(hs_frame);
1199     while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1200       fst.next();
1201     }
1202     if (fst.current()->sp() != stack_pointer) {
1203       THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "stack frame not found")
1204     }
1205   }
1206 
1207   int frame_number = 0;
1208   vframe* vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1209   if (hs_frame != NULL) {
1210     // look for the correct vframe within the stack frame if one is given
1211     int last_frame_number = HotSpotStackFrameReference::frameNumber(hs_frame);
1212     while (frame_number < last_frame_number) {
1213       if (vf->is_top()) {
1214         THROW_MSG_NULL(vmSymbols::java_lang_IllegalStateException(), "invalid frame number")
1215       }
1216       vf = vf->sender();
1217       frame_number ++;
1218     }
1219     // move one frame forward
1220     if (vf->is_top()) {
1221       if (fst.is_done()) {
1222         return NULL;
1223       }
1224       fst.next();
1225       vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1226       frame_number = 0;
1227     } else {
1228       vf = vf->sender();
1229       frame_number++;
1230     }
1231   }
1232 
1233   while (true) {
1234     // look for the given method
1235     while (true) {
1236       StackValueCollection* locals = NULL;
1237       if (vf->is_compiled_frame()) {
1238         // compiled method frame
1239         compiledVFrame* cvf = compiledVFrame::cast(vf);
1240         if (methods == NULL || matches(methods, cvf->method())) {
1241           if (initialSkip > 0) {
1242             initialSkip --;
1243           } else {
1244             ScopeDesc* scope = cvf->scope();
1245             // native wrapper do not have a scope
1246             if (scope != NULL && scope->objects() != NULL) {
1247               bool realloc_failures = Deoptimization::realloc_objects(thread, fst.current(), scope->objects(), THREAD);
1248               Deoptimization::reassign_fields(fst.current(), fst.register_map(), scope->objects(), realloc_failures, false);
1249 
1250               GrowableArray<ScopeValue*>* local_values = scope->locals();
1251               typeArrayHandle array = oopFactory::new_boolArray(local_values->length(), thread);
1252               for (int i = 0; i < local_values->length(); i++) {
1253                 ScopeValue* value = local_values->at(i);
1254                 if (value->is_object()) {
1255                   array->bool_at_put(i, true);
1256                 }
1257               }
1258               HotSpotStackFrameReference::set_localIsVirtual(result, array());
1259             } else {
1260               HotSpotStackFrameReference::set_localIsVirtual(result, NULL);
1261             }
1262 
1263             locals = cvf->locals();
1264             HotSpotStackFrameReference::set_bci(result, cvf->bci());
1265             oop method = CompilerToVM::get_jvmci_method(cvf->method(), CHECK_NULL);
1266             HotSpotStackFrameReference::set_method(result, method);
1267           }
1268         }
1269       } else if (vf->is_interpreted_frame()) {
1270         // interpreted method frame
1271         interpretedVFrame* ivf = interpretedVFrame::cast(vf);
1272         if (methods == NULL || matches(methods, ivf->method())) {
1273           if (initialSkip > 0) {
1274             initialSkip --;
1275           } else {
1276             locals = ivf->locals();
1277             HotSpotStackFrameReference::set_bci(result, ivf->bci());
1278             oop method = CompilerToVM::get_jvmci_method(ivf->method(), CHECK_NULL);
1279             HotSpotStackFrameReference::set_method(result, method);
1280             HotSpotStackFrameReference::set_localIsVirtual(result, NULL);
1281           }
1282         }
1283       }
1284 
1285       // locals != NULL means that we found a matching frame and result is already partially initialized
1286       if (locals != NULL) {
1287         HotSpotStackFrameReference::set_compilerToVM(result, JNIHandles::resolve(compilerToVM));
1288         HotSpotStackFrameReference::set_stackPointer(result, (jlong) fst.current()->sp());
1289         HotSpotStackFrameReference::set_frameNumber(result, frame_number);
1290 
1291         // initialize the locals array
1292         objArrayHandle array = oopFactory::new_objectArray(locals->size(), thread);
1293         for (int i = 0; i < locals->size(); i++) {
1294           StackValue* var = locals->at(i);
1295           if (var->type() == T_OBJECT) {
1296             array->obj_at_put(i, locals->at(i)->get_obj()());
1297           }
1298         }
1299         HotSpotStackFrameReference::set_locals(result, array());
1300 
1301         return JNIHandles::make_local(thread, result());
1302       }
1303 
1304       if (vf->is_top()) {
1305         break;
1306       }
1307       frame_number++;
1308       vf = vf->sender();
1309     } // end of vframe loop
1310 
1311     if (fst.is_done()) {
1312       break;
1313     }
1314     fst.next();
1315     vf = vframe::new_vframe(fst.current(), fst.register_map(), thread);
1316     frame_number = 0;
1317   } // end of frame loop
1318 
1319   // the end was reached without finding a matching method
1320   return NULL;
1321 C2V_END
1322 
1323 C2V_VMENTRY(void, resolveInvokeDynamicInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1324   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1325   CallInfo callInfo;
1326   LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokedynamic, CHECK);
1327   ConstantPoolCacheEntry* cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(index);
1328   cp_cache_entry->set_dynamic_call(cp, callInfo);
1329 C2V_END
1330 
1331 C2V_VMENTRY(void, resolveInvokeHandleInPool, (JNIEnv*, jobject, jobject jvmci_constant_pool, jint index))
1332   constantPoolHandle cp = CompilerToVM::asConstantPool(jvmci_constant_pool);
1333   KlassHandle holder = cp->klass_ref_at(index, CHECK);
1334   Symbol* name = cp->name_ref_at(index);
1335   if (MethodHandles::is_signature_polymorphic_name(holder(), name)) {
1336     CallInfo callInfo;
1337     LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, Bytecodes::_invokehandle, CHECK);
1338     ConstantPoolCacheEntry* cp_cache_entry = cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1339     cp_cache_entry->set_method_handle(cp, callInfo);
1340   }
1341 C2V_END
1342 
1343 C2V_VMENTRY(jobject, getSignaturePolymorphicHolders, (JNIEnv*, jobject))
1344   objArrayHandle holders = oopFactory::new_objArray(SystemDictionary::String_klass(), 2, CHECK_NULL);
1345   Handle mh = java_lang_String::create_from_str("Ljava/lang/invoke/MethodHandle;", CHECK_NULL);
1346   Handle vh = java_lang_String::create_from_str("Ljava/lang/invoke/VarHandle;", CHECK_NULL);
1347   holders->obj_at_put(0, mh());
1348   holders->obj_at_put(1, vh());
1349   return JNIHandles::make_local(THREAD, holders());
1350 C2V_END
1351 
1352 C2V_VMENTRY(jboolean, shouldDebugNonSafepoints, (JNIEnv*, jobject))
1353   //see compute_recording_non_safepoints in debugInfroRec.cpp
1354   if (JvmtiExport::should_post_compiled_method_load() && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
1355     return true;
1356   }
1357   return DebugNonSafepoints;
1358 C2V_END
1359 
1360 // public native void materializeVirtualObjects(HotSpotStackFrameReference stackFrame, boolean invalidate);
1361 C2V_VMENTRY(void, materializeVirtualObjects, (JNIEnv*, jobject, jobject hs_frame, bool invalidate))
1362   ResourceMark rm;
1363 
1364   if (hs_frame == NULL) {
1365     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "stack frame is null")
1366   }
1367 
1368   HotSpotStackFrameReference::klass()->initialize(thread);
1369 
1370   // look for the given stack frame
1371   StackFrameStream fst(thread);
1372   intptr_t* stack_pointer = (intptr_t*) HotSpotStackFrameReference::stackPointer(hs_frame);
1373   while (fst.current()->sp() != stack_pointer && !fst.is_done()) {
1374     fst.next();
1375   }
1376   if (fst.current()->sp() != stack_pointer) {
1377     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found")
1378   }
1379 
1380   if (invalidate) {
1381     if (!fst.current()->is_compiled_frame()) {
1382       THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1383     }
1384     assert(fst.current()->cb()->is_nmethod(), "nmethod expected");
1385     ((nmethod*) fst.current()->cb())->make_not_entrant();
1386   }
1387   Deoptimization::deoptimize(thread, *fst.current(), fst.register_map(), Deoptimization::Reason_none);
1388   // look for the frame again as it has been updated by deopt (pc, deopt state...)
1389   StackFrameStream fstAfterDeopt(thread);
1390   while (fstAfterDeopt.current()->sp() != stack_pointer && !fstAfterDeopt.is_done()) {
1391     fstAfterDeopt.next();
1392   }
1393   if (fstAfterDeopt.current()->sp() != stack_pointer) {
1394     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "stack frame not found after deopt")
1395   }
1396 
1397   vframe* vf = vframe::new_vframe(fstAfterDeopt.current(), fstAfterDeopt.register_map(), thread);
1398   if (!vf->is_compiled_frame()) {
1399     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "compiled stack frame expected")
1400   }
1401 
1402   GrowableArray<compiledVFrame*>* virtualFrames = new GrowableArray<compiledVFrame*>(10);
1403   while (true) {
1404     assert(vf->is_compiled_frame(), "Wrong frame type");
1405     virtualFrames->push(compiledVFrame::cast(vf));
1406     if (vf->is_top()) {
1407       break;
1408     }
1409     vf = vf->sender();
1410   }
1411 
1412   int last_frame_number = HotSpotStackFrameReference::frameNumber(hs_frame);
1413   if (last_frame_number >= virtualFrames->length()) {
1414     THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "invalid frame number")
1415   }
1416 
1417   // Reallocate the non-escaping objects and restore their fields.
1418   assert (virtualFrames->at(last_frame_number)->scope() != NULL,"invalid scope");
1419   GrowableArray<ScopeValue*>* objects = virtualFrames->at(last_frame_number)->scope()->objects();
1420 
1421   if (objects == NULL) {
1422     // no objects to materialize
1423     return;
1424   }
1425 
1426   bool realloc_failures = Deoptimization::realloc_objects(thread, fstAfterDeopt.current(), objects, THREAD);
1427   Deoptimization::reassign_fields(fstAfterDeopt.current(), fstAfterDeopt.register_map(), objects, realloc_failures, false);
1428 
1429   for (int frame_index = 0; frame_index < virtualFrames->length(); frame_index++) {
1430     compiledVFrame* cvf = virtualFrames->at(frame_index);
1431 
1432     GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
1433     StackValueCollection* locals = cvf->locals();
1434 
1435     if (locals != NULL) {
1436       for (int i2 = 0; i2 < locals->size(); i2++) {
1437         StackValue* var = locals->at(i2);
1438         if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) {
1439           jvalue val;
1440           val.l = (jobject) locals->at(i2)->get_obj()();
1441           cvf->update_local(T_OBJECT, i2, val);
1442         }
1443       }
1444     }
1445   }
1446 
1447   // all locals are materialized by now
1448   HotSpotStackFrameReference::set_localIsVirtual(hs_frame, NULL);
1449 
1450   // update the locals array
1451   objArrayHandle array = HotSpotStackFrameReference::locals(hs_frame);
1452   StackValueCollection* locals = virtualFrames->at(last_frame_number)->locals();
1453   for (int i = 0; i < locals->size(); i++) {
1454     StackValue* var = locals->at(i);
1455     if (var->type() == T_OBJECT) {
1456       array->obj_at_put(i, locals->at(i)->get_obj()());
1457     }
1458   }
1459 C2V_END
1460 
1461 C2V_VMENTRY(void, writeDebugOutput, (JNIEnv*, jobject, jbyteArray bytes, jint offset, jint length))
1462   if (bytes == NULL) {
1463     THROW(vmSymbols::java_lang_NullPointerException());
1464   }
1465   typeArrayOop array = (typeArrayOop) JNIHandles::resolve(bytes);
1466 
1467   // Check if offset and length are non negative.
1468   if (offset < 0 || length < 0) {
1469     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1470   }
1471   // Check if the range is valid.
1472   if ((((unsigned int) length + (unsigned int) offset) > (unsigned int) array->length())) {
1473     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
1474   }
1475   while (length > 0) {
1476     jbyte* start = array->byte_at_addr(offset);
1477     tty->write((char*) start, MIN2(length, O_BUFLEN));
1478     length -= O_BUFLEN;
1479     offset += O_BUFLEN;
1480   }
1481 C2V_END
1482 
1483 C2V_VMENTRY(void, flushDebugOutput, (JNIEnv*, jobject))
1484   tty->flush();
1485 C2V_END
1486 
1487 C2V_VMENTRY(int, methodDataProfileDataSize, (JNIEnv*, jobject, jlong metaspace_method_data, jint position))
1488   ResourceMark rm;
1489   MethodData* mdo = CompilerToVM::asMethodData(metaspace_method_data);
1490   ProfileData* profile_data = mdo->data_at(position);
1491   if (mdo->is_valid(profile_data)) {
1492     return profile_data->size_in_bytes();
1493   }
1494   DataLayout* data    = mdo->extra_data_base();
1495   DataLayout* end   = mdo->extra_data_limit();
1496   for (;; data = mdo->next_extra(data)) {
1497     assert(data < end, "moved past end of extra data");
1498     profile_data = data->data_in();
1499     if (mdo->dp_to_di(profile_data->dp()) == position) {
1500       return profile_data->size_in_bytes();
1501     }
1502   }
1503   THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), err_msg("Invalid profile data position %d", position));
1504 C2V_END
1505 
1506 C2V_VMENTRY(jlong, getFingerprint, (JNIEnv*, jobject, jlong metaspace_klass))
1507   Klass *k = CompilerToVM::asKlass(metaspace_klass);
1508   if (k->is_instance_klass()) {
1509     return InstanceKlass::cast(k)->get_stored_fingerprint();
1510   } else {
1511     return 0;
1512   }
1513 C2V_END
1514 
1515 C2V_VMENTRY(int, interpreterFrameSize, (JNIEnv*, jobject, jobject bytecode_frame_handle))
1516   if (bytecode_frame_handle == NULL) {
1517     THROW_0(vmSymbols::java_lang_NullPointerException());
1518   }
1519 
1520   oop top_bytecode_frame = JNIHandles::resolve_non_null(bytecode_frame_handle);
1521   oop bytecode_frame = top_bytecode_frame;
1522   int size = 0;
1523   int callee_parameters = 0;
1524   int callee_locals = 0;
1525   Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1526   int extra_args = method->max_stack() - BytecodeFrame::numStack(bytecode_frame);
1527 
1528   while (bytecode_frame != NULL) {
1529     int locks = BytecodeFrame::numLocks(bytecode_frame);
1530     int temps = BytecodeFrame::numStack(bytecode_frame);
1531     bool is_top_frame = (bytecode_frame == top_bytecode_frame);
1532     Method* method = getMethodFromHotSpotMethod(BytecodePosition::method(bytecode_frame));
1533 
1534     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
1535                                                                  temps + callee_parameters,
1536                                                                  extra_args,
1537                                                                  locks,
1538                                                                  callee_parameters,
1539                                                                  callee_locals,
1540                                                                  is_top_frame);
1541     size += frame_size;
1542 
1543     callee_parameters = method->size_of_parameters();
1544     callee_locals = method->max_locals();
1545     extra_args = 0;
1546     bytecode_frame = BytecodePosition::caller(bytecode_frame);
1547   }
1548   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
1549 C2V_END
1550 
1551 C2V_VMENTRY(void, compileToBytecode, (JNIEnv*, jobject, jobject lambda_form_handle))
1552   Handle lambda_form = JNIHandles::resolve_non_null(lambda_form_handle);
1553   if (lambda_form->is_a(SystemDictionary::LambdaForm_klass())) {
1554     TempNewSymbol compileToBytecode = SymbolTable::new_symbol("compileToBytecode", CHECK);
1555     JavaValue result(T_VOID);
1556     JavaCalls::call_special(&result, lambda_form, SystemDictionary::LambdaForm_klass(), compileToBytecode, vmSymbols::void_method_signature(), CHECK);
1557   } else {
1558     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1559                 err_msg("Unexpected type: %s", lambda_form->klass()->external_name()));
1560   }
1561 C2V_END
1562 
1563 #define CC (char*)  /*cast a literal from (const char*)*/
1564 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &(c2v_ ## f))
1565 
1566 #define STRING                "Ljava/lang/String;"
1567 #define OBJECT                "Ljava/lang/Object;"
1568 #define CLASS                 "Ljava/lang/Class;"
1569 #define EXECUTABLE            "Ljava/lang/reflect/Executable;"
1570 #define STACK_TRACE_ELEMENT   "Ljava/lang/StackTraceElement;"
1571 #define INSTALLED_CODE        "Ljdk/vm/ci/code/InstalledCode;"
1572 #define TARGET_DESCRIPTION    "Ljdk/vm/ci/code/TargetDescription;"
1573 #define BYTECODE_FRAME        "Ljdk/vm/ci/code/BytecodeFrame;"
1574 #define RESOLVED_METHOD       "Ljdk/vm/ci/meta/ResolvedJavaMethod;"
1575 #define HS_RESOLVED_METHOD    "Ljdk/vm/ci/hotspot/HotSpotResolvedJavaMethodImpl;"
1576 #define HS_RESOLVED_KLASS     "Ljdk/vm/ci/hotspot/HotSpotResolvedObjectTypeImpl;"
1577 #define HS_CONSTANT_POOL      "Ljdk/vm/ci/hotspot/HotSpotConstantPool;"
1578 #define HS_COMPILED_CODE      "Ljdk/vm/ci/hotspot/HotSpotCompiledCode;"
1579 #define HS_CONFIG             "Ljdk/vm/ci/hotspot/HotSpotVMConfig;"
1580 #define HS_METADATA           "Ljdk/vm/ci/hotspot/HotSpotMetaData;"
1581 #define HS_STACK_FRAME_REF    "Ljdk/vm/ci/hotspot/HotSpotStackFrameReference;"
1582 #define HS_SPECULATION_LOG    "Ljdk/vm/ci/hotspot/HotSpotSpeculationLog;"
1583 #define METASPACE_METHOD_DATA "J"
1584 
1585 JNINativeMethod CompilerToVM::methods[] = {
1586   {CC "getBytecode",                                  CC "(" HS_RESOLVED_METHOD ")[B",                                                      FN_PTR(getBytecode)},
1587   {CC "getExceptionTableStart",                       CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getExceptionTableStart)},
1588   {CC "getExceptionTableLength",                      CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getExceptionTableLength)},
1589   {CC "findUniqueConcreteMethod",                     CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")" HS_RESOLVED_METHOD,                   FN_PTR(findUniqueConcreteMethod)},
1590   {CC "getImplementor",                               CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_KLASS,                                       FN_PTR(getImplementor)},
1591   {CC "getStackTraceElement",                         CC "(" HS_RESOLVED_METHOD "I)" STACK_TRACE_ELEMENT,                                   FN_PTR(getStackTraceElement)},
1592   {CC "methodIsIgnoredBySecurityStackWalk",           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(methodIsIgnoredBySecurityStackWalk)},
1593   {CC "doNotInlineOrCompile",                         CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(doNotInlineOrCompile)},
1594   {CC "canInlineMethod",                              CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(canInlineMethod)},
1595   {CC "shouldInlineMethod",                           CC "(" HS_RESOLVED_METHOD ")Z",                                                       FN_PTR(shouldInlineMethod)},
1596   {CC "lookupType",                                   CC "(" STRING CLASS "Z)" HS_RESOLVED_KLASS,                                           FN_PTR(lookupType)},
1597   {CC "lookupNameInPool",                             CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupNameInPool)},
1598   {CC "lookupNameAndTypeRefIndexInPool",              CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupNameAndTypeRefIndexInPool)},
1599   {CC "lookupSignatureInPool",                        CC "(" HS_CONSTANT_POOL "I)" STRING,                                                  FN_PTR(lookupSignatureInPool)},
1600   {CC "lookupKlassRefIndexInPool",                    CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(lookupKlassRefIndexInPool)},
1601   {CC "lookupKlassInPool",                            CC "(" HS_CONSTANT_POOL "I)Ljava/lang/Object;",                                       FN_PTR(lookupKlassInPool)},
1602   {CC "lookupAppendixInPool",                         CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(lookupAppendixInPool)},
1603   {CC "lookupMethodInPool",                           CC "(" HS_CONSTANT_POOL "IB)" HS_RESOLVED_METHOD,                                     FN_PTR(lookupMethodInPool)},
1604   {CC "constantPoolRemapInstructionOperandFromCache", CC "(" HS_CONSTANT_POOL "I)I",                                                        FN_PTR(constantPoolRemapInstructionOperandFromCache)},
1605   {CC "resolveConstantInPool",                        CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolveConstantInPool)},
1606   {CC "resolvePossiblyCachedConstantInPool",          CC "(" HS_CONSTANT_POOL "I)" OBJECT,                                                  FN_PTR(resolvePossiblyCachedConstantInPool)},
1607   {CC "resolveTypeInPool",                            CC "(" HS_CONSTANT_POOL "I)" HS_RESOLVED_KLASS,                                       FN_PTR(resolveTypeInPool)},
1608   {CC "resolveFieldInPool",                           CC "(" HS_CONSTANT_POOL "I" HS_RESOLVED_METHOD "B[J)" HS_RESOLVED_KLASS,              FN_PTR(resolveFieldInPool)},
1609   {CC "resolveInvokeDynamicInPool",                   CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeDynamicInPool)},
1610   {CC "resolveInvokeHandleInPool",                    CC "(" HS_CONSTANT_POOL "I)V",                                                        FN_PTR(resolveInvokeHandleInPool)},
1611   {CC "resolveMethod",                                CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD, FN_PTR(resolveMethod)},
1612   {CC "getSignaturePolymorphicHolders",               CC "()[" STRING,                                                                      FN_PTR(getSignaturePolymorphicHolders)},
1613   {CC "getVtableIndexForInterfaceMethod",             CC "(" HS_RESOLVED_KLASS HS_RESOLVED_METHOD ")I",                                     FN_PTR(getVtableIndexForInterfaceMethod)},
1614   {CC "getClassInitializer",                          CC "(" HS_RESOLVED_KLASS ")" HS_RESOLVED_METHOD,                                      FN_PTR(getClassInitializer)},
1615   {CC "hasFinalizableSubclass",                       CC "(" HS_RESOLVED_KLASS ")Z",                                                        FN_PTR(hasFinalizableSubclass)},
1616   {CC "getMaxCallTargetOffset",                       CC "(J)J",                                                                            FN_PTR(getMaxCallTargetOffset)},
1617   {CC "asResolvedJavaMethod",                         CC "(" EXECUTABLE ")" HS_RESOLVED_METHOD,                                             FN_PTR(asResolvedJavaMethod)},
1618   {CC "getResolvedJavaMethod",                        CC "(Ljava/lang/Object;J)" HS_RESOLVED_METHOD,                                        FN_PTR(getResolvedJavaMethod)},
1619   {CC "getConstantPool",                              CC "(Ljava/lang/Object;)" HS_CONSTANT_POOL,                                           FN_PTR(getConstantPool)},
1620   {CC "getResolvedJavaType",                          CC "(Ljava/lang/Object;JZ)" HS_RESOLVED_KLASS,                                        FN_PTR(getResolvedJavaType)},
1621   {CC "readConfiguration",                            CC "()[" OBJECT,                                                                      FN_PTR(readConfiguration)},
1622   {CC "installCode",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE INSTALLED_CODE HS_SPECULATION_LOG ")I",    FN_PTR(installCode)},
1623   {CC "getMetadata",                                  CC "(" TARGET_DESCRIPTION HS_COMPILED_CODE HS_METADATA ")I",                          FN_PTR(getMetadata)},
1624   {CC "resetCompilationStatistics",                   CC "()V",                                                                             FN_PTR(resetCompilationStatistics)},
1625   {CC "disassembleCodeBlob",                          CC "(" INSTALLED_CODE ")" STRING,                                                     FN_PTR(disassembleCodeBlob)},
1626   {CC "executeInstalledCode",                         CC "([" OBJECT INSTALLED_CODE ")" OBJECT,                                             FN_PTR(executeInstalledCode)},
1627   {CC "getLineNumberTable",                           CC "(" HS_RESOLVED_METHOD ")[J",                                                      FN_PTR(getLineNumberTable)},
1628   {CC "getLocalVariableTableStart",                   CC "(" HS_RESOLVED_METHOD ")J",                                                       FN_PTR(getLocalVariableTableStart)},
1629   {CC "getLocalVariableTableLength",                  CC "(" HS_RESOLVED_METHOD ")I",                                                       FN_PTR(getLocalVariableTableLength)},
1630   {CC "reprofile",                                    CC "(" HS_RESOLVED_METHOD ")V",                                                       FN_PTR(reprofile)},
1631   {CC "invalidateInstalledCode",                      CC "(" INSTALLED_CODE ")V",                                                           FN_PTR(invalidateInstalledCode)},
1632   {CC "collectCounters",                              CC "()[J",                                                                            FN_PTR(collectCounters)},
1633   {CC "allocateCompileId",                            CC "(" HS_RESOLVED_METHOD "I)I",                                                      FN_PTR(allocateCompileId)},
1634   {CC "isMature",                                     CC "(" METASPACE_METHOD_DATA ")Z",                                                    FN_PTR(isMature)},
1635   {CC "hasCompiledCodeForOSR",                        CC "(" HS_RESOLVED_METHOD "II)Z",                                                     FN_PTR(hasCompiledCodeForOSR)},
1636   {CC "getSymbol",                                    CC "(J)" STRING,                                                                      FN_PTR(getSymbol)},
1637   {CC "getNextStackFrame",                            CC "(" HS_STACK_FRAME_REF "[" RESOLVED_METHOD "I)" HS_STACK_FRAME_REF,                FN_PTR(getNextStackFrame)},
1638   {CC "materializeVirtualObjects",                    CC "(" HS_STACK_FRAME_REF "Z)V",                                                      FN_PTR(materializeVirtualObjects)},
1639   {CC "shouldDebugNonSafepoints",                     CC "()Z",                                                                             FN_PTR(shouldDebugNonSafepoints)},
1640   {CC "writeDebugOutput",                             CC "([BII)V",                                                                         FN_PTR(writeDebugOutput)},
1641   {CC "flushDebugOutput",                             CC "()V",                                                                             FN_PTR(flushDebugOutput)},
1642   {CC "methodDataProfileDataSize",                    CC "(JI)I",                                                                           FN_PTR(methodDataProfileDataSize)},
1643   {CC "getFingerprint",                               CC "(J)J",                                                                            FN_PTR(getFingerprint)},
1644   {CC "interpreterFrameSize",                         CC "(" BYTECODE_FRAME ")I",                                                           FN_PTR(interpreterFrameSize)},
1645   {CC "compileToBytecode",                            CC "(" OBJECT ")V",                                                                   FN_PTR(compileToBytecode)},
1646 };
1647 
1648 int CompilerToVM::methods_count() {
1649   return sizeof(methods) / sizeof(JNINativeMethod);
1650 }
--- EOF ---