1 /*
   2  * Copyright (c) 2012, 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 "asm/codeBuffer.hpp"
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "jvmci/jvmciRuntime.hpp"
  31 #include "jvmci/jvmciCompilerToVM.hpp"
  32 #include "jvmci/jvmciCompiler.hpp"
  33 #include "jvmci/jvmciJavaClasses.hpp"
  34 #include "jvmci/jvmciEnv.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "oops/objArrayOop.inline.hpp"
  39 #include "prims/jvm.h"
  40 #include "runtime/biasedLocking.hpp"
  41 #include "runtime/interfaceSupport.hpp"
  42 #include "runtime/reflection.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "utilities/debug.hpp"
  45 #include "utilities/defaultStream.hpp"
  46 
  47 #if defined(_MSC_VER)
  48 #define strtoll _strtoi64
  49 #endif
  50 
  51 jobject JVMCIRuntime::_HotSpotJVMCIRuntime_instance = NULL;
  52 bool JVMCIRuntime::_HotSpotJVMCIRuntime_initialized = false;
  53 bool JVMCIRuntime::_well_known_classes_initialized = false;
  54 int JVMCIRuntime::_trivial_prefixes_count = 0;
  55 char** JVMCIRuntime::_trivial_prefixes = NULL;
  56 bool JVMCIRuntime::_shutdown_called = false;
  57 
  58 BasicType JVMCIRuntime::kindToBasicType(Handle kind, TRAPS) {
  59   if (kind.is_null()) {
  60     THROW_(vmSymbols::java_lang_NullPointerException(), T_ILLEGAL);
  61   }
  62   jchar ch = JavaKind::typeChar(kind);
  63   switch(ch) {
  64     case 'z': return T_BOOLEAN;
  65     case 'b': return T_BYTE;
  66     case 's': return T_SHORT;
  67     case 'c': return T_CHAR;
  68     case 'i': return T_INT;
  69     case 'f': return T_FLOAT;
  70     case 'j': return T_LONG;
  71     case 'd': return T_DOUBLE;
  72     case 'a': return T_OBJECT;
  73     case '-': return T_ILLEGAL;
  74     default:
  75       JVMCI_ERROR_(T_ILLEGAL, "unexpected Kind: %c", ch);
  76   }
  77 }
  78 
  79 // Simple helper to see if the caller of a runtime stub which
  80 // entered the VM has been deoptimized
  81 
  82 static bool caller_is_deopted() {
  83   JavaThread* thread = JavaThread::current();
  84   RegisterMap reg_map(thread, false);
  85   frame runtime_frame = thread->last_frame();
  86   frame caller_frame = runtime_frame.sender(&reg_map);
  87   assert(caller_frame.is_compiled_frame(), "must be compiled");
  88   return caller_frame.is_deoptimized_frame();
  89 }
  90 
  91 // Stress deoptimization
  92 static void deopt_caller() {
  93   if ( !caller_is_deopted()) {
  94     JavaThread* thread = JavaThread::current();
  95     RegisterMap reg_map(thread, false);
  96     frame runtime_frame = thread->last_frame();
  97     frame caller_frame = runtime_frame.sender(&reg_map);
  98     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
  99     assert(caller_is_deopted(), "Must be deoptimized");
 100   }
 101 }
 102 
 103 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance(JavaThread* thread, Klass* klass))
 104   JRT_BLOCK;
 105   assert(klass->is_klass(), "not a class");
 106   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
 107   instanceKlassHandle h(thread, klass);
 108   h->check_valid_for_instantiation(true, CHECK);
 109   // make sure klass is initialized
 110   h->initialize(CHECK);
 111   // allocate instance and return via TLS
 112   oop obj = h->allocate_instance(CHECK);
 113   thread->set_vm_result(obj);
 114   JRT_BLOCK_END;
 115 
 116   if (ReduceInitialCardMarks) {
 117     new_store_pre_barrier(thread);
 118   }
 119 JRT_END
 120 
 121 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length))
 122   JRT_BLOCK;
 123   // Note: no handle for klass needed since they are not used
 124   //       anymore after new_objArray() and no GC can happen before.
 125   //       (This may have to change if this code changes!)
 126   assert(array_klass->is_klass(), "not a class");
 127   oop obj;
 128   if (array_klass->is_typeArray_klass()) {
 129     BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
 130     obj = oopFactory::new_typeArray(elt_type, length, CHECK);
 131   } else {
 132     Handle holder(THREAD, array_klass->klass_holder()); // keep the klass alive
 133     Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
 134     obj = oopFactory::new_objArray(elem_klass, length, CHECK);
 135   }
 136   thread->set_vm_result(obj);
 137   // This is pretty rare but this runtime patch is stressful to deoptimization
 138   // if we deoptimize here so force a deopt to stress the path.
 139   if (DeoptimizeALot) {
 140     static int deopts = 0;
 141     // Alternate between deoptimizing and raising an error (which will also cause a deopt)
 142     if (deopts++ % 2 == 0) {
 143       ResourceMark rm(THREAD);
 144       THROW(vmSymbols::java_lang_OutOfMemoryError());
 145     } else {
 146       deopt_caller();
 147     }
 148   }
 149   JRT_BLOCK_END;
 150 
 151   if (ReduceInitialCardMarks) {
 152     new_store_pre_barrier(thread);
 153   }
 154 JRT_END
 155 
 156 void JVMCIRuntime::new_store_pre_barrier(JavaThread* thread) {
 157   // After any safepoint, just before going back to compiled code,
 158   // we inform the GC that we will be doing initializing writes to
 159   // this object in the future without emitting card-marks, so
 160   // GC may take any compensating steps.
 161   // NOTE: Keep this code consistent with GraphKit::store_barrier.
 162 
 163   oop new_obj = thread->vm_result();
 164   if (new_obj == NULL)  return;
 165 
 166   assert(Universe::heap()->can_elide_tlab_store_barriers(),
 167          "compiler must check this first");
 168   // GC may decide to give back a safer copy of new_obj.
 169   new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj);
 170   thread->set_vm_result(new_obj);
 171 }
 172 
 173 JRT_ENTRY(void, JVMCIRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims))
 174   assert(klass->is_klass(), "not a class");
 175   assert(rank >= 1, "rank must be nonzero");
 176   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
 177   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
 178   thread->set_vm_result(obj);
 179 JRT_END
 180 
 181 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length))
 182   oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
 183   thread->set_vm_result(obj);
 184 JRT_END
 185 
 186 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror))
 187   instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(type_mirror));
 188 
 189   if (klass == NULL) {
 190     ResourceMark rm(THREAD);
 191     THROW(vmSymbols::java_lang_InstantiationException());
 192   }
 193 
 194   // Create new instance (the receiver)
 195   klass->check_valid_for_instantiation(false, CHECK);
 196 
 197   // Make sure klass gets initialized
 198   klass->initialize(CHECK);
 199 
 200   oop obj = klass->allocate_instance(CHECK);
 201   thread->set_vm_result(obj);
 202 JRT_END
 203 
 204 extern void vm_exit(int code);
 205 
 206 // Enter this method from compiled code handler below. This is where we transition
 207 // to VM mode. This is done as a helper routine so that the method called directly
 208 // from compiled code does not have to transition to VM. This allows the entry
 209 // method to see if the nmethod that we have just looked up a handler for has
 210 // been deoptimized while we were in the vm. This simplifies the assembly code
 211 // cpu directories.
 212 //
 213 // We are entering here from exception stub (via the entry method below)
 214 // If there is a compiled exception handler in this method, we will continue there;
 215 // otherwise we will unwind the stack and continue at the caller of top frame method
 216 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
 217 // control the area where we can allow a safepoint. After we exit the safepoint area we can
 218 // check to see if the handler we are going to return is now in a nmethod that has
 219 // been deoptimized. If that is the case we return the deopt blob
 220 // unpack_with_exception entry instead. This makes life for the exception blob easier
 221 // because making that same check and diverting is painful from assembly language.
 222 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, nmethod*& nm))
 223   // Reset method handle flag.
 224   thread->set_is_method_handle_return(false);
 225 
 226   Handle exception(thread, ex);
 227   nm = CodeCache::find_nmethod(pc);
 228   assert(nm != NULL, "this is not a compiled method");
 229   // Adjust the pc as needed/
 230   if (nm->is_deopt_pc(pc)) {
 231     RegisterMap map(thread, false);
 232     frame exception_frame = thread->last_frame().sender(&map);
 233     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
 234     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
 235     pc = exception_frame.pc();
 236   }
 237 #ifdef ASSERT
 238   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
 239   assert(exception->is_oop(), "just checking");
 240   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 241   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
 242     if (ExitVMOnVerifyError) vm_exit(-1);
 243     ShouldNotReachHere();
 244   }
 245 #endif
 246 
 247   // Check the stack guard pages and reenable them if necessary and there is
 248   // enough space on the stack to do so.  Use fast exceptions only if the guard
 249   // pages are enabled.
 250   bool guard_pages_enabled = thread->stack_guards_enabled();
 251   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
 252 
 253   if (JvmtiExport::can_post_on_exceptions()) {
 254     // To ensure correct notification of exception catches and throws
 255     // we have to deoptimize here.  If we attempted to notify the
 256     // catches and throws during this exception lookup it's possible
 257     // we could deoptimize on the way out of the VM and end back in
 258     // the interpreter at the throw site.  This would result in double
 259     // notifications since the interpreter would also notify about
 260     // these same catches and throws as it unwound the frame.
 261 
 262     RegisterMap reg_map(thread);
 263     frame stub_frame = thread->last_frame();
 264     frame caller_frame = stub_frame.sender(&reg_map);
 265 
 266     // We don't really want to deoptimize the nmethod itself since we
 267     // can actually continue in the exception handler ourselves but I
 268     // don't see an easy way to have the desired effect.
 269     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
 270     assert(caller_is_deopted(), "Must be deoptimized");
 271 
 272     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 273   }
 274 
 275   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
 276   if (guard_pages_enabled) {
 277     address fast_continuation = nm->handler_for_exception_and_pc(exception, pc);
 278     if (fast_continuation != NULL) {
 279       // Set flag if return address is a method handle call site.
 280       thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
 281       return fast_continuation;
 282     }
 283   }
 284 
 285   // If the stack guard pages are enabled, check whether there is a handler in
 286   // the current method.  Otherwise (guard pages disabled), force an unwind and
 287   // skip the exception cache update (i.e., just leave continuation==NULL).
 288   address continuation = NULL;
 289   if (guard_pages_enabled) {
 290 
 291     // New exception handling mechanism can support inlined methods
 292     // with exception handlers since the mappings are from PC to PC
 293 
 294     // debugging support
 295     // tracing
 296     if (log_is_enabled(Info, exceptions)) {
 297       ResourceMark rm;
 298       stringStream tempst;
 299       tempst.print("compiled method <%s>\n"
 300                    " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
 301                    nm->method()->print_value_string(), p2i(pc), p2i(thread));
 302       Exceptions::log_exception(exception, tempst);
 303     }
 304     // for AbortVMOnException flag
 305     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
 306 
 307     // Clear out the exception oop and pc since looking up an
 308     // exception handler can cause class loading, which might throw an
 309     // exception and those fields are expected to be clear during
 310     // normal bytecode execution.
 311     thread->clear_exception_oop_and_pc();
 312 
 313     continuation = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, false, false);
 314     // If an exception was thrown during exception dispatch, the exception oop may have changed
 315     thread->set_exception_oop(exception());
 316     thread->set_exception_pc(pc);
 317 
 318     // the exception cache is used only by non-implicit exceptions
 319     if (continuation != NULL && !SharedRuntime::deopt_blob()->contains(continuation)) {
 320       nm->add_handler_for_exception_and_pc(exception, pc, continuation);
 321     }
 322   }
 323 
 324   // Set flag if return address is a method handle call site.
 325   thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
 326 
 327   if (log_is_enabled(Info, exceptions)) {
 328     ResourceMark rm;
 329     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
 330                          " for exception thrown at PC " PTR_FORMAT,
 331                          p2i(thread), p2i(continuation), p2i(pc));
 332   }
 333 
 334   return continuation;
 335 JRT_END
 336 
 337 // Enter this method from compiled code only if there is a Java exception handler
 338 // in the method handling the exception.
 339 // We are entering here from exception stub. We don't do a normal VM transition here.
 340 // We do it in a helper. This is so we can check to see if the nmethod we have just
 341 // searched for an exception handler has been deoptimized in the meantime.
 342 address JVMCIRuntime::exception_handler_for_pc(JavaThread* thread) {
 343   oop exception = thread->exception_oop();
 344   address pc = thread->exception_pc();
 345   // Still in Java mode
 346   DEBUG_ONLY(ResetNoHandleMark rnhm);
 347   nmethod* nm = NULL;
 348   address continuation = NULL;
 349   {
 350     // Enter VM mode by calling the helper
 351     ResetNoHandleMark rnhm;
 352     continuation = exception_handler_for_pc_helper(thread, exception, pc, nm);
 353   }
 354   // Back in JAVA, use no oops DON'T safepoint
 355 
 356   // Now check to see if the compiled method we were called from is now deoptimized.
 357   // If so we must return to the deopt blob and deoptimize the nmethod
 358   if (nm != NULL && caller_is_deopted()) {
 359     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
 360   }
 361 
 362   assert(continuation != NULL, "no handler found");
 363   return continuation;
 364 }
 365 
 366 JRT_ENTRY(void, JVMCIRuntime::create_null_exception(JavaThread* thread))
 367   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_NullPointerException());
 368   thread->set_vm_result(PENDING_EXCEPTION);
 369   CLEAR_PENDING_EXCEPTION;
 370 JRT_END
 371 
 372 JRT_ENTRY(void, JVMCIRuntime::create_out_of_bounds_exception(JavaThread* thread, jint index))
 373   char message[jintAsStringSize];
 374   sprintf(message, "%d", index);
 375   SharedRuntime::throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), message);
 376   thread->set_vm_result(PENDING_EXCEPTION);
 377   CLEAR_PENDING_EXCEPTION;
 378 JRT_END
 379 
 380 JRT_ENTRY_NO_ASYNC(void, JVMCIRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 381   IF_TRACE_jvmci_3 {
 382     char type[O_BUFLEN];
 383     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 384     markOop mark = obj->mark();
 385     TRACE_jvmci_3("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock));
 386     tty->flush();
 387   }
 388 #ifdef ASSERT
 389   if (PrintBiasedLockingStatistics) {
 390     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 391   }
 392 #endif
 393   Handle h_obj(thread, obj);
 394   assert(h_obj()->is_oop(), "must be NULL or an object");
 395   if (UseBiasedLocking) {
 396     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 397     ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
 398   } else {
 399     if (JVMCIUseFastLocking) {
 400       // When using fast locking, the compiled code has already tried the fast case
 401       ObjectSynchronizer::slow_enter(h_obj, lock, THREAD);
 402     } else {
 403       ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD);
 404     }
 405   }
 406   TRACE_jvmci_3("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj));
 407 JRT_END
 408 
 409 JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock))
 410   assert(thread == JavaThread::current(), "threads must correspond");
 411   assert(thread->last_Java_sp(), "last_Java_sp must be set");
 412   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
 413   EXCEPTION_MARK;
 414 
 415 #ifdef DEBUG
 416   if (!obj->is_oop()) {
 417     ResetNoHandleMark rhm;
 418     nmethod* method = thread->last_frame().cb()->as_nmethod_or_null();
 419     if (method != NULL) {
 420       tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj));
 421     }
 422     thread->print_stack_on(tty);
 423     assert(false, "invalid lock object pointer dected");
 424   }
 425 #endif
 426 
 427   if (JVMCIUseFastLocking) {
 428     // When using fast locking, the compiled code has already tried the fast case
 429     ObjectSynchronizer::slow_exit(obj, lock, THREAD);
 430   } else {
 431     ObjectSynchronizer::fast_exit(obj, lock, THREAD);
 432   }
 433   IF_TRACE_jvmci_3 {
 434     char type[O_BUFLEN];
 435     obj->klass()->name()->as_C_string(type, O_BUFLEN);
 436     TRACE_jvmci_3("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock));
 437     tty->flush();
 438   }
 439 JRT_END
 440 
 441 JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
 442   ttyLocker ttyl;
 443 
 444   if (obj == NULL) {
 445     tty->print("NULL");
 446   } else if (obj->is_oop_or_null(true) && (!as_string || !java_lang_String::is_instance(obj))) {
 447     if (obj->is_oop_or_null(true)) {
 448       char buf[O_BUFLEN];
 449       tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
 450     } else {
 451       tty->print(INTPTR_FORMAT, p2i(obj));
 452     }
 453   } else {
 454     ResourceMark rm;
 455     assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
 456     char *buf = java_lang_String::as_utf8_string(obj);
 457     tty->print_raw(buf);
 458   }
 459   if (newline) {
 460     tty->cr();
 461   }
 462 JRT_END
 463 
 464 JRT_LEAF(void, JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj))
 465   thread->satb_mark_queue().enqueue(obj);
 466 JRT_END
 467 
 468 JRT_LEAF(void, JVMCIRuntime::write_barrier_post(JavaThread* thread, void* card_addr))
 469   thread->dirty_card_queue().enqueue(card_addr);
 470 JRT_END
 471 
 472 JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
 473   bool ret = true;
 474   if(!Universe::heap()->is_in_closed_subset(parent)) {
 475     tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
 476     parent->print();
 477     ret=false;
 478   }
 479   if(!Universe::heap()->is_in_closed_subset(child)) {
 480     tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
 481     child->print();
 482     ret=false;
 483   }
 484   return (jint)ret;
 485 JRT_END
 486 
 487 JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value))
 488   ResourceMark rm;
 489   const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
 490   char *detail_msg = NULL;
 491   if (format != 0L) {
 492     const char* buf = (char*) (address) format;
 493     size_t detail_msg_length = strlen(buf) * 2;
 494     detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
 495     jio_snprintf(detail_msg, detail_msg_length, buf, value);
 496     report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
 497   } else {
 498     report_vm_error(__FILE__, __LINE__, error_msg);
 499   }
 500 JRT_END
 501 
 502 JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
 503   oop exception = thread->exception_oop();
 504   assert(exception != NULL, "npe");
 505   thread->set_exception_oop(NULL);
 506   thread->set_exception_pc(0);
 507   return exception;
 508 JRT_END
 509 
 510 PRAGMA_DIAG_PUSH
 511 PRAGMA_FORMAT_NONLITERAL_IGNORED
 512 JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3))
 513   ResourceMark rm;
 514   assert(format != NULL && java_lang_String::is_instance(format), "must be");
 515   char *buf = java_lang_String::as_utf8_string(format);
 516   tty->print((const char*)buf, v1, v2, v3);
 517 JRT_END
 518 PRAGMA_DIAG_POP
 519 
 520 static void decipher(jlong v, bool ignoreZero) {
 521   if (v != 0 || !ignoreZero) {
 522     void* p = (void *)(address) v;
 523     CodeBlob* cb = CodeCache::find_blob(p);
 524     if (cb) {
 525       if (cb->is_nmethod()) {
 526         char buf[O_BUFLEN];
 527         tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin()));
 528         return;
 529       }
 530       cb->print_value_on(tty);
 531       return;
 532     }
 533     if (Universe::heap()->is_in(p)) {
 534       oop obj = oop(p);
 535       obj->print_value_on(tty);
 536       return;
 537     }
 538     tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
 539   }
 540 }
 541 
 542 PRAGMA_DIAG_PUSH
 543 PRAGMA_FORMAT_NONLITERAL_IGNORED
 544 JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
 545   ResourceMark rm;
 546   const char *buf = (const char*) (address) format;
 547   if (vmError) {
 548     if (buf != NULL) {
 549       fatal(buf, v1, v2, v3);
 550     } else {
 551       fatal("<anonymous error>");
 552     }
 553   } else if (buf != NULL) {
 554     tty->print(buf, v1, v2, v3);
 555   } else {
 556     assert(v2 == 0, "v2 != 0");
 557     assert(v3 == 0, "v3 != 0");
 558     decipher(v1, false);
 559   }
 560 JRT_END
 561 PRAGMA_DIAG_POP
 562 
 563 JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
 564   union {
 565       jlong l;
 566       jdouble d;
 567       jfloat f;
 568   } uu;
 569   uu.l = value;
 570   switch (typeChar) {
 571     case 'z': tty->print(value == 0 ? "false" : "true"); break;
 572     case 'b': tty->print("%d", (jbyte) value); break;
 573     case 'c': tty->print("%c", (jchar) value); break;
 574     case 's': tty->print("%d", (jshort) value); break;
 575     case 'i': tty->print("%d", (jint) value); break;
 576     case 'f': tty->print("%f", uu.f); break;
 577     case 'j': tty->print(JLONG_FORMAT, value); break;
 578     case 'd': tty->print("%lf", uu.d); break;
 579     default: assert(false, "unknown typeChar"); break;
 580   }
 581   if (newline) {
 582     tty->cr();
 583   }
 584 JRT_END
 585 
 586 JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj))
 587   return (jint) obj->identity_hash();
 588 JRT_END
 589 
 590 JRT_ENTRY(jboolean, JVMCIRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted))
 591   // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
 592   // This locking requires thread_in_vm which is why this method cannot be JRT_LEAF.
 593   Handle receiverHandle(thread, receiver);
 594   MutexLockerEx ml(thread->threadObj() == (void*)receiver ? NULL : Threads_lock);
 595   JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle());
 596   if (receiverThread == NULL) {
 597     // The other thread may exit during this process, which is ok so return false.
 598     return JNI_FALSE;
 599   } else {
 600     return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0);
 601   }
 602 JRT_END
 603 
 604 JRT_ENTRY(jint, JVMCIRuntime::test_deoptimize_call_int(JavaThread* thread, int value))
 605   deopt_caller();
 606   return value;
 607 JRT_END
 608 
 609 // private static JVMCIRuntime JVMCI.initializeRuntime()
 610 JVM_ENTRY(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
 611   if (!EnableJVMCI) {
 612     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled")
 613   }
 614   JVMCIRuntime::initialize_HotSpotJVMCIRuntime(CHECK_NULL);
 615   jobject ret = JVMCIRuntime::get_HotSpotJVMCIRuntime_jobject(CHECK_NULL);
 616   return ret;
 617 JVM_END
 618 
 619 Handle JVMCIRuntime::callStatic(const char* className, const char* methodName, const char* signature, JavaCallArguments* args, TRAPS) {
 620   guarantee(!_HotSpotJVMCIRuntime_initialized, "cannot reinitialize HotSpotJVMCIRuntime");
 621 
 622   TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_(Handle()));
 623   KlassHandle klass = SystemDictionary::resolve_or_fail(name, true, CHECK_(Handle()));
 624   TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_(Handle()));
 625   TempNewSymbol sig = SymbolTable::new_symbol(signature, CHECK_(Handle()));
 626   JavaValue result(T_OBJECT);
 627   if (args == NULL) {
 628     JavaCalls::call_static(&result, klass, runtime, sig, CHECK_(Handle()));
 629   } else {
 630     JavaCalls::call_static(&result, klass, runtime, sig, args, CHECK_(Handle()));
 631   }
 632   return Handle((oop)result.get_jobject());
 633 }
 634 
 635 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(TRAPS) {
 636   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 637     ResourceMark rm;
 638 #ifdef ASSERT
 639     // This should only be called in the context of the JVMCI class being initialized
 640     TempNewSymbol name = SymbolTable::new_symbol("jdk/vm/ci/runtime/JVMCI", CHECK);
 641     Klass* k = SystemDictionary::resolve_or_null(name, CHECK);
 642     instanceKlassHandle klass = InstanceKlass::cast(k);
 643     assert(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD),
 644            "HotSpotJVMCIRuntime initialization should only be triggered through JVMCI initialization");
 645 #endif
 646 
 647     Handle result = callStatic("jdk/vm/ci/hotspot/HotSpotJVMCIRuntime",
 648                                "runtime",
 649                                "()Ljdk/vm/ci/hotspot/HotSpotJVMCIRuntime;", NULL, CHECK);
 650     objArrayOop trivial_prefixes = HotSpotJVMCIRuntime::trivialPrefixes(result);
 651     if (trivial_prefixes != NULL) {
 652       char** prefixes = NEW_C_HEAP_ARRAY(char*, trivial_prefixes->length(), mtCompiler);
 653       for (int i = 0; i < trivial_prefixes->length(); i++) {
 654         oop str = trivial_prefixes->obj_at(i);
 655         if (str == NULL) {
 656           THROW(vmSymbols::java_lang_NullPointerException());
 657         } else {
 658           prefixes[i] = strdup(java_lang_String::as_utf8_string(str));
 659         }
 660       }
 661       _trivial_prefixes = prefixes;
 662       _trivial_prefixes_count = trivial_prefixes->length();
 663     }
 664     _HotSpotJVMCIRuntime_initialized = true;
 665     _HotSpotJVMCIRuntime_instance = JNIHandles::make_global(result());
 666   }
 667 }
 668 
 669 void JVMCIRuntime::initialize_JVMCI(TRAPS) {
 670   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
 671     callStatic("jdk/vm/ci/runtime/JVMCI",
 672                "getRuntime",
 673                "()Ljdk/vm/ci/runtime/JVMCIRuntime;", NULL, CHECK);
 674   }
 675   assert(_HotSpotJVMCIRuntime_initialized == true, "what?");
 676 }
 677 
 678 void JVMCIRuntime::initialize_well_known_classes(TRAPS) {
 679   if (JVMCIRuntime::_well_known_classes_initialized == false) {
 680     SystemDictionary::WKID scan = SystemDictionary::FIRST_JVMCI_WKID;
 681     SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_JVMCI_WKID, scan, CHECK);
 682     JVMCIJavaClasses::compute_offsets(CHECK);
 683     JVMCIRuntime::_well_known_classes_initialized = true;
 684   }
 685 }
 686 
 687 void JVMCIRuntime::metadata_do(void f(Metadata*)) {
 688   // For simplicity, the existence of HotSpotJVMCIMetaAccessContext in
 689   // the SystemDictionary well known classes should ensure the other
 690   // classes have already been loaded, so make sure their order in the
 691   // table enforces that.
 692   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedJavaMethodImpl) <
 693          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 694   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotConstantPool) <
 695          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 696   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedObjectTypeImpl) <
 697          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
 698 
 699   if (HotSpotJVMCIMetaAccessContext::klass() == NULL ||
 700       !HotSpotJVMCIMetaAccessContext::klass()->is_linked()) {
 701     // Nothing could be registered yet
 702     return;
 703   }
 704 
 705   // WeakReference<HotSpotJVMCIMetaAccessContext>[]
 706   objArrayOop allContexts = HotSpotJVMCIMetaAccessContext::allContexts();
 707   if (allContexts == NULL) {
 708     return;
 709   }
 710 
 711   // These must be loaded at this point but the linking state doesn't matter.
 712   assert(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass() != NULL, "must be loaded");
 713   assert(SystemDictionary::HotSpotConstantPool_klass() != NULL, "must be loaded");
 714   assert(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass() != NULL, "must be loaded");
 715 
 716   for (int i = 0; i < allContexts->length(); i++) {
 717     oop ref = allContexts->obj_at(i);
 718     if (ref != NULL) {
 719       oop referent = java_lang_ref_Reference::referent(ref);
 720       if (referent != NULL) {
 721         // Chunked Object[] with last element pointing to next chunk
 722         objArrayOop metadataRoots = HotSpotJVMCIMetaAccessContext::metadataRoots(referent);
 723         while (metadataRoots != NULL) {
 724           for (int typeIndex = 0; typeIndex < metadataRoots->length() - 1; typeIndex++) {
 725             oop reference = metadataRoots->obj_at(typeIndex);
 726             if (reference == NULL) {
 727               continue;
 728             }
 729             oop metadataRoot = java_lang_ref_Reference::referent(reference);
 730             if (metadataRoot == NULL) {
 731               continue;
 732             }
 733             if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
 734               Method* method = CompilerToVM::asMethod(metadataRoot);
 735               f(method);
 736             } else if (metadataRoot->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
 737               ConstantPool* constantPool = CompilerToVM::asConstantPool(metadataRoot);
 738               f(constantPool);
 739             } else if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
 740               Klass* klass = CompilerToVM::asKlass(metadataRoot);
 741               f(klass);
 742             } else {
 743               metadataRoot->print();
 744               ShouldNotReachHere();
 745             }
 746           }
 747           metadataRoots = (objArrayOop)metadataRoots->obj_at(metadataRoots->length() - 1);
 748           assert(metadataRoots == NULL || metadataRoots->is_objArray(), "wrong type");
 749         }
 750       }
 751     }
 752   }
 753 }
 754 
 755 // private static void CompilerToVM.registerNatives()
 756 JVM_ENTRY(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
 757   if (!EnableJVMCI) {
 758     THROW_MSG(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled");
 759   }
 760 
 761 #ifdef _LP64
 762 #ifndef TARGET_ARCH_sparc
 763   uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end();
 764   uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024;
 765   guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)");
 766 #endif // TARGET_ARCH_sparc
 767 #else
 768   fatal("check TLAB allocation code for address space conflicts");
 769 #endif
 770 
 771   JVMCIRuntime::initialize_well_known_classes(CHECK);
 772 
 773   {
 774     ThreadToNativeFromVM trans(thread);
 775     env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count());
 776   }
 777 JVM_END
 778 
 779 #define CHECK_WARN_ABORT_(message) THREAD); \
 780   if (HAS_PENDING_EXCEPTION) { \
 781     warning(message); \
 782     char buf[512]; \
 783     jio_snprintf(buf, 512, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
 784     JVMCIRuntime::abort_on_pending_exception(PENDING_EXCEPTION, buf); \
 785     return; \
 786   } \
 787   (void)(0
 788 
 789 void JVMCIRuntime::shutdown(TRAPS) {
 790   if (_HotSpotJVMCIRuntime_instance != NULL) {
 791     _shutdown_called = true;
 792     HandleMark hm(THREAD);
 793     Handle receiver = get_HotSpotJVMCIRuntime(CHECK);
 794     JavaValue result(T_VOID);
 795     JavaCallArguments args;
 796     args.push_oop(receiver);
 797     JavaCalls::call_special(&result, receiver->klass(), vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK);
 798   }
 799 }
 800 
 801 bool JVMCIRuntime::treat_as_trivial(Method* method) {
 802   if (_HotSpotJVMCIRuntime_initialized) {
 803     for (int i = 0; i < _trivial_prefixes_count; i++) {
 804       if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) {
 805         return true;
 806       }
 807     }
 808   }
 809   return false;
 810 }