1 /*
2  * Copyright (c) 2012, 2020, 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 "classfile/symbolTable.hpp"
27 #include "compiler/compileBroker.hpp"
28 #include "gc/shared/oopStorage.inline.hpp"
29 #include "jvmci/jniAccessMark.inline.hpp"
30 #include "jvmci/jvmciCompilerToVM.hpp"
31 #include "jvmci/jvmciRuntime.hpp"
32 #include "jvmci/metadataHandles.hpp"
33 #include "logging/log.hpp"
34 #include "memory/oopFactory.hpp"
35 #include "memory/universe.hpp"
36 #include "oops/constantPool.inline.hpp"
37 #include "oops/klass.inline.hpp"
38 #include "oops/method.inline.hpp"
39 #include "oops/objArrayKlass.hpp"
40 #include "oops/oop.inline.hpp"
41 #include "oops/typeArrayOop.inline.hpp"
42 #include "prims/jvmtiExport.hpp"
43 #include "prims/methodHandles.hpp"
44 #include "runtime/atomic.hpp"
45 #include "runtime/biasedLocking.hpp"
46 #include "runtime/deoptimization.hpp"
47 #include "runtime/fieldDescriptor.inline.hpp"
48 #include "runtime/frame.inline.hpp"
49 #include "runtime/java.hpp"
50 #include "runtime/jniHandles.inline.hpp"
51 #include "runtime/reflectionUtils.hpp"
52 #include "runtime/sharedRuntime.hpp"
53 #if INCLUDE_G1GC
54 #include "gc/g1/g1ThreadLocalData.hpp"
55 #endif // INCLUDE_G1GC
56 
57 // Simple helper to see if the caller of a runtime stub which
58 // entered the VM has been deoptimized
59 
caller_is_deopted()60 static bool caller_is_deopted() {
61   JavaThread* thread = JavaThread::current();
62   RegisterMap reg_map(thread, false);
63   frame runtime_frame = thread->last_frame();
64   frame caller_frame = runtime_frame.sender(&reg_map);
65   assert(caller_frame.is_compiled_frame(), "must be compiled");
66   return caller_frame.is_deoptimized_frame();
67 }
68 
69 // Stress deoptimization
deopt_caller()70 static void deopt_caller() {
71   if ( !caller_is_deopted()) {
72     JavaThread* thread = JavaThread::current();
73     RegisterMap reg_map(thread, false);
74     frame runtime_frame = thread->last_frame();
75     frame caller_frame = runtime_frame.sender(&reg_map);
76     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
77     assert(caller_is_deopted(), "Must be deoptimized");
78   }
79 }
80 
81 // Manages a scope for a JVMCI runtime call that attempts a heap allocation.
82 // If there is a pending nonasync exception upon closing the scope and the runtime
83 // call is of the variety where allocation failure returns NULL without an
84 // exception, the following action is taken:
85 //   1. The pending nonasync exception is cleared
86 //   2. NULL is written to JavaThread::_vm_result
87 //   3. Checks that an OutOfMemoryError is Universe::out_of_memory_error_retry().
88 class RetryableAllocationMark: public StackObj {
89  private:
90   JavaThread* _thread;
91  public:
RetryableAllocationMark(JavaThread * thread,bool activate)92   RetryableAllocationMark(JavaThread* thread, bool activate) {
93     if (activate) {
94       assert(!thread->in_retryable_allocation(), "retryable allocation scope is non-reentrant");
95       _thread = thread;
96       _thread->set_in_retryable_allocation(true);
97     } else {
98       _thread = NULL;
99     }
100   }
~RetryableAllocationMark()101   ~RetryableAllocationMark() {
102     if (_thread != NULL) {
103       _thread->set_in_retryable_allocation(false);
104       JavaThread* THREAD = _thread;
105       if (HAS_PENDING_EXCEPTION) {
106         oop ex = PENDING_EXCEPTION;
107         // Do not clear probable async exceptions.
108         CLEAR_PENDING_NONASYNC_EXCEPTION;
109         oop retry_oome = Universe::out_of_memory_error_retry();
110         if (ex->is_a(retry_oome->klass()) && retry_oome != ex) {
111           ResourceMark rm;
112           fatal("Unexpected exception in scope of retryable allocation: " INTPTR_FORMAT " of type %s", p2i(ex), ex->klass()->external_name());
113         }
114         _thread->set_vm_result(NULL);
115       }
116     }
117   }
118 };
119 
120 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance_common(JavaThread* thread, Klass* klass, bool null_on_fail))
121   JRT_BLOCK;
122   assert(klass->is_klass(), "not a class");
123   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
124   InstanceKlass* h = InstanceKlass::cast(klass);
125   {
126     RetryableAllocationMark ram(thread, null_on_fail);
127     h->check_valid_for_instantiation(true, CHECK);
128     oop obj;
129     if (null_on_fail) {
130       if (!h->is_initialized()) {
131         // Cannot re-execute class initialization without side effects
132         // so return without attempting the initialization
133         return;
134       }
135     } else {
136       // make sure klass is initialized
137       h->initialize(CHECK);
138     }
139     // allocate instance and return via TLS
140     obj = h->allocate_instance(CHECK);
141     thread->set_vm_result(obj);
142   }
143   JRT_BLOCK_END;
144   SharedRuntime::on_slowpath_allocation_exit(thread);
145 JRT_END
146 
147 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array_common(JavaThread* thread, Klass* array_klass, jint length, bool null_on_fail))
148   JRT_BLOCK;
149   // Note: no handle for klass needed since they are not used
150   //       anymore after new_objArray() and no GC can happen before.
151   //       (This may have to change if this code changes!)
152   assert(array_klass->is_klass(), "not a class");
153   oop obj;
154   if (array_klass->is_typeArray_klass()) {
155     BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
156     RetryableAllocationMark ram(thread, null_on_fail);
157     obj = oopFactory::new_typeArray(elt_type, length, CHECK);
158   } else {
159     Handle holder(THREAD, array_klass->klass_holder()); // keep the klass alive
160     Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
161     RetryableAllocationMark ram(thread, null_on_fail);
162     obj = oopFactory::new_objArray(elem_klass, length, CHECK);
163   }
164   thread->set_vm_result(obj);
165   // This is pretty rare but this runtime patch is stressful to deoptimization
166   // if we deoptimize here so force a deopt to stress the path.
167   if (DeoptimizeALot) {
168     static int deopts = 0;
169     // Alternate between deoptimizing and raising an error (which will also cause a deopt)
170     if (deopts++ % 2 == 0) {
171       if (null_on_fail) {
172         return;
173       } else {
174         ResourceMark rm(THREAD);
175         THROW(vmSymbols::java_lang_OutOfMemoryError());
176       }
177     } else {
178       deopt_caller();
179     }
180   }
181   JRT_BLOCK_END;
182   SharedRuntime::on_slowpath_allocation_exit(thread);
183 JRT_END
184 
185 JRT_ENTRY(void, JVMCIRuntime::new_multi_array_common(JavaThread* thread, Klass* klass, int rank, jint* dims, bool null_on_fail))
186   assert(klass->is_klass(), "not a class");
187   assert(rank >= 1, "rank must be nonzero");
188   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
189   RetryableAllocationMark ram(thread, null_on_fail);
190   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
191   thread->set_vm_result(obj);
192 JRT_END
193 
194 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array_common(JavaThread* thread, oopDesc* element_mirror, jint length, bool null_on_fail))
195   RetryableAllocationMark ram(thread, null_on_fail);
196   oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
197   thread->set_vm_result(obj);
198 JRT_END
199 
200 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance_common(JavaThread* thread, oopDesc* type_mirror, bool null_on_fail))
201   InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(type_mirror));
202 
203   if (klass == NULL) {
204     ResourceMark rm(THREAD);
205     THROW(vmSymbols::java_lang_InstantiationException());
206   }
207   RetryableAllocationMark ram(thread, null_on_fail);
208 
209   // Create new instance (the receiver)
210   klass->check_valid_for_instantiation(false, CHECK);
211 
212   if (null_on_fail) {
213     if (!klass->is_initialized()) {
214       // Cannot re-execute class initialization without side effects
215       // so return without attempting the initialization
216       return;
217     }
218   } else {
219     // Make sure klass gets initialized
220     klass->initialize(CHECK);
221   }
222 
223   oop obj = klass->allocate_instance(CHECK);
224   thread->set_vm_result(obj);
225 JRT_END
226 
227 extern void vm_exit(int code);
228 
229 // Enter this method from compiled code handler below. This is where we transition
230 // to VM mode. This is done as a helper routine so that the method called directly
231 // from compiled code does not have to transition to VM. This allows the entry
232 // method to see if the nmethod that we have just looked up a handler for has
233 // been deoptimized while we were in the vm. This simplifies the assembly code
234 // cpu directories.
235 //
236 // We are entering here from exception stub (via the entry method below)
237 // If there is a compiled exception handler in this method, we will continue there;
238 // otherwise we will unwind the stack and continue at the caller of top frame method
239 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
240 // control the area where we can allow a safepoint. After we exit the safepoint area we can
241 // check to see if the handler we are going to return is now in a nmethod that has
242 // been deoptimized. If that is the case we return the deopt blob
243 // unpack_with_exception entry instead. This makes life for the exception blob easier
244 // because making that same check and diverting is painful from assembly language.
245 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, CompiledMethod*& cm))
246   // Reset method handle flag.
247   thread->set_is_method_handle_return(false);
248 
249   Handle exception(thread, ex);
250   cm = CodeCache::find_compiled(pc);
251   assert(cm != NULL, "this is not a compiled method");
252   // Adjust the pc as needed/
253   if (cm->is_deopt_pc(pc)) {
254     RegisterMap map(thread, false);
255     frame exception_frame = thread->last_frame().sender(&map);
256     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
257     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
258     pc = exception_frame.pc();
259   }
260 #ifdef ASSERT
261   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
262   assert(oopDesc::is_oop(exception()), "just checking");
263   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
264   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
265     if (ExitVMOnVerifyError) vm_exit(-1);
266     ShouldNotReachHere();
267   }
268 #endif
269 
270   // debugging support
271   // tracing
272   if (log_is_enabled(Info, exceptions)) {
273     ResourceMark rm;
274     stringStream tempst;
275     assert(cm->method() != NULL, "Unexpected null method()");
276     tempst.print("JVMCI compiled method <%s>\n"
277                  " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
278                  cm->method()->print_value_string(), p2i(pc), p2i(thread));
279     Exceptions::log_exception(exception, tempst.as_string());
280   }
281   // for AbortVMOnException flag
282   Exceptions::debug_check_abort(exception);
283 
284   // Check the stack guard pages and reenable them if necessary and there is
285   // enough space on the stack to do so.  Use fast exceptions only if the guard
286   // pages are enabled.
287   bool guard_pages_enabled = thread->stack_overflow_state()->reguard_stack_if_needed();
288 
289   if (JvmtiExport::can_post_on_exceptions()) {
290     // To ensure correct notification of exception catches and throws
291     // we have to deoptimize here.  If we attempted to notify the
292     // catches and throws during this exception lookup it's possible
293     // we could deoptimize on the way out of the VM and end back in
294     // the interpreter at the throw site.  This would result in double
295     // notifications since the interpreter would also notify about
296     // these same catches and throws as it unwound the frame.
297 
298     RegisterMap reg_map(thread);
299     frame stub_frame = thread->last_frame();
300     frame caller_frame = stub_frame.sender(&reg_map);
301 
302     // We don't really want to deoptimize the nmethod itself since we
303     // can actually continue in the exception handler ourselves but I
304     // don't see an easy way to have the desired effect.
305     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
306     assert(caller_is_deopted(), "Must be deoptimized");
307 
308     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
309   }
310 
311   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
312   if (guard_pages_enabled) {
313     address fast_continuation = cm->handler_for_exception_and_pc(exception, pc);
314     if (fast_continuation != NULL) {
315       // Set flag if return address is a method handle call site.
316       thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
317       return fast_continuation;
318     }
319   }
320 
321   // If the stack guard pages are enabled, check whether there is a handler in
322   // the current method.  Otherwise (guard pages disabled), force an unwind and
323   // skip the exception cache update (i.e., just leave continuation==NULL).
324   address continuation = NULL;
325   if (guard_pages_enabled) {
326 
327     // New exception handling mechanism can support inlined methods
328     // with exception handlers since the mappings are from PC to PC
329 
330     // Clear out the exception oop and pc since looking up an
331     // exception handler can cause class loading, which might throw an
332     // exception and those fields are expected to be clear during
333     // normal bytecode execution.
334     thread->clear_exception_oop_and_pc();
335 
336     bool recursive_exception = false;
337     continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false, recursive_exception);
338     // If an exception was thrown during exception dispatch, the exception oop may have changed
339     thread->set_exception_oop(exception());
340     thread->set_exception_pc(pc);
341 
342     // The exception cache is used only for non-implicit exceptions
343     // Update the exception cache only when another exception did
344     // occur during the computation of the compiled exception handler
345     // (e.g., when loading the class of the catch type).
346     // Checking for exception oop equality is not
347     // sufficient because some exceptions are pre-allocated and reused.
348     if (continuation != NULL && !recursive_exception && !SharedRuntime::deopt_blob()->contains(continuation)) {
349       cm->add_handler_for_exception_and_pc(exception, pc, continuation);
350     }
351   }
352 
353   // Set flag if return address is a method handle call site.
354   thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
355 
356   if (log_is_enabled(Info, exceptions)) {
357     ResourceMark rm;
358     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
359                          " for exception thrown at PC " PTR_FORMAT,
360                          p2i(thread), p2i(continuation), p2i(pc));
361   }
362 
363   return continuation;
364 JRT_END
365 
366 // Enter this method from compiled code only if there is a Java exception handler
367 // in the method handling the exception.
368 // We are entering here from exception stub. We don't do a normal VM transition here.
369 // We do it in a helper. This is so we can check to see if the nmethod we have just
370 // searched for an exception handler has been deoptimized in the meantime.
exception_handler_for_pc(JavaThread * thread)371 address JVMCIRuntime::exception_handler_for_pc(JavaThread* thread) {
372   oop exception = thread->exception_oop();
373   address pc = thread->exception_pc();
374   // Still in Java mode
375   DEBUG_ONLY(ResetNoHandleMark rnhm);
376   CompiledMethod* cm = NULL;
377   address continuation = NULL;
378   {
379     // Enter VM mode by calling the helper
380     ResetNoHandleMark rnhm;
381     continuation = exception_handler_for_pc_helper(thread, exception, pc, cm);
382   }
383   // Back in JAVA, use no oops DON'T safepoint
384 
385   // Now check to see if the compiled method we were called from is now deoptimized.
386   // If so we must return to the deopt blob and deoptimize the nmethod
387   if (cm != NULL && caller_is_deopted()) {
388     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
389   }
390 
391   assert(continuation != NULL, "no handler found");
392   return continuation;
393 }
394 
395 JRT_BLOCK_ENTRY(void, JVMCIRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock))
396   SharedRuntime::monitor_enter_helper(obj, lock, thread);
397 JRT_END
398 
399 JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock))
400   assert(thread->last_Java_sp(), "last_Java_sp must be set");
401   assert(oopDesc::is_oop(obj), "invalid lock object pointer dected");
402   SharedRuntime::monitor_exit_helper(obj, lock, thread);
403 JRT_END
404 
405 // Object.notify() fast path, caller does slow path
406 JRT_LEAF(jboolean, JVMCIRuntime::object_notify(JavaThread *thread, oopDesc* obj))
407 
408   // Very few notify/notifyAll operations find any threads on the waitset, so
409   // the dominant fast-path is to simply return.
410   // Relatedly, it's critical that notify/notifyAll be fast in order to
411   // reduce lock hold times.
412   if (!SafepointSynchronize::is_synchronizing()) {
413     if (ObjectSynchronizer::quick_notify(obj, thread, false)) {
414       return true;
415     }
416   }
417   return false; // caller must perform slow path
418 
419 JRT_END
420 
421 // Object.notifyAll() fast path, caller does slow path
422 JRT_LEAF(jboolean, JVMCIRuntime::object_notifyAll(JavaThread *thread, oopDesc* obj))
423 
424   if (!SafepointSynchronize::is_synchronizing() ) {
425     if (ObjectSynchronizer::quick_notify(obj, thread, true)) {
426       return true;
427     }
428   }
429   return false; // caller must perform slow path
430 
431 JRT_END
432 
433 JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_and_post_jvmti_exception(JavaThread* thread, const char* exception, const char* message))
434   JRT_BLOCK;
435   TempNewSymbol symbol = SymbolTable::new_symbol(exception);
436   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
437   JRT_BLOCK_END;
438   return caller_is_deopted();
439 JRT_END
440 
441 JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_klass_external_name_exception(JavaThread* thread, const char* exception, Klass* klass))
442   JRT_BLOCK;
443   ResourceMark rm(thread);
444   TempNewSymbol symbol = SymbolTable::new_symbol(exception);
445   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, klass->external_name());
446   JRT_BLOCK_END;
447   return caller_is_deopted();
448 JRT_END
449 
450 JRT_BLOCK_ENTRY(int, JVMCIRuntime::throw_class_cast_exception(JavaThread* thread, const char* exception, Klass* caster_klass, Klass* target_klass))
451   JRT_BLOCK;
452   ResourceMark rm(thread);
453   const char* message = SharedRuntime::generate_class_cast_message(caster_klass, target_klass);
454   TempNewSymbol symbol = SymbolTable::new_symbol(exception);
455   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
456   JRT_BLOCK_END;
457   return caller_is_deopted();
458 JRT_END
459 
460 JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
461   ttyLocker ttyl;
462 
463   if (obj == NULL) {
464     tty->print("NULL");
465   } else if (oopDesc::is_oop_or_null(obj, true) && (!as_string || !java_lang_String::is_instance(obj))) {
466     if (oopDesc::is_oop_or_null(obj, true)) {
467       char buf[O_BUFLEN];
468       tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
469     } else {
470       tty->print(INTPTR_FORMAT, p2i(obj));
471     }
472   } else {
473     ResourceMark rm;
474     assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
475     char *buf = java_lang_String::as_utf8_string(obj);
476     tty->print_raw(buf);
477   }
478   if (newline) {
479     tty->cr();
480   }
481 JRT_END
482 
483 #if INCLUDE_G1GC
484 
485 JRT_LEAF(void, JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj))
486   G1ThreadLocalData::satb_mark_queue(thread).enqueue(obj);
487 JRT_END
488 
489 JRT_LEAF(void, JVMCIRuntime::write_barrier_post(JavaThread* thread, void* card_addr))
490   G1ThreadLocalData::dirty_card_queue(thread).enqueue(card_addr);
491 JRT_END
492 
493 #endif // INCLUDE_G1GC
494 
495 JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
496   bool ret = true;
497   if(!Universe::heap()->is_in(parent)) {
498     tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
499     parent->print();
500     ret=false;
501   }
502   if(!Universe::heap()->is_in(child)) {
503     tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
504     child->print();
505     ret=false;
506   }
507   return (jint)ret;
508 JRT_END
509 
510 JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value))
511   ResourceMark rm;
512   const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
513   char *detail_msg = NULL;
514   if (format != 0L) {
515     const char* buf = (char*) (address) format;
516     size_t detail_msg_length = strlen(buf) * 2;
517     detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
518     jio_snprintf(detail_msg, detail_msg_length, buf, value);
519   }
520   report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
521 JRT_END
522 
523 JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
524   oop exception = thread->exception_oop();
525   assert(exception != NULL, "npe");
526   thread->set_exception_oop(NULL);
527   thread->set_exception_pc(0);
528   return exception;
529 JRT_END
530 
531 PRAGMA_DIAG_PUSH
532 PRAGMA_FORMAT_NONLITERAL_IGNORED
533 JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, const char* format, jlong v1, jlong v2, jlong v3))
534   ResourceMark rm;
535   tty->print(format, v1, v2, v3);
536 JRT_END
537 PRAGMA_DIAG_POP
538 
decipher(jlong v,bool ignoreZero)539 static void decipher(jlong v, bool ignoreZero) {
540   if (v != 0 || !ignoreZero) {
541     void* p = (void *)(address) v;
542     CodeBlob* cb = CodeCache::find_blob(p);
543     if (cb) {
544       if (cb->is_nmethod()) {
545         char buf[O_BUFLEN];
546         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()));
547         return;
548       }
549       cb->print_value_on(tty);
550       return;
551     }
552     if (Universe::heap()->is_in(p)) {
553       oop obj = oop(p);
554       obj->print_value_on(tty);
555       return;
556     }
557     tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
558   }
559 }
560 
561 PRAGMA_DIAG_PUSH
562 PRAGMA_FORMAT_NONLITERAL_IGNORED
563 JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
564   ResourceMark rm;
565   const char *buf = (const char*) (address) format;
566   if (vmError) {
567     if (buf != NULL) {
568       fatal(buf, v1, v2, v3);
569     } else {
570       fatal("<anonymous error>");
571     }
572   } else if (buf != NULL) {
573     tty->print(buf, v1, v2, v3);
574   } else {
575     assert(v2 == 0, "v2 != 0");
576     assert(v3 == 0, "v3 != 0");
577     decipher(v1, false);
578   }
579 JRT_END
580 PRAGMA_DIAG_POP
581 
582 JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
583   union {
584       jlong l;
585       jdouble d;
586       jfloat f;
587   } uu;
588   uu.l = value;
589   switch (typeChar) {
590     case 'Z': tty->print(value == 0 ? "false" : "true"); break;
591     case 'B': tty->print("%d", (jbyte) value); break;
592     case 'C': tty->print("%c", (jchar) value); break;
593     case 'S': tty->print("%d", (jshort) value); break;
594     case 'I': tty->print("%d", (jint) value); break;
595     case 'F': tty->print("%f", uu.f); break;
596     case 'J': tty->print(JLONG_FORMAT, value); break;
597     case 'D': tty->print("%lf", uu.d); break;
598     default: assert(false, "unknown typeChar"); break;
599   }
600   if (newline) {
601     tty->cr();
602   }
603 JRT_END
604 
605 JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj))
606   return (jint) obj->identity_hash();
607 JRT_END
608 
609 JRT_ENTRY(jint, JVMCIRuntime::test_deoptimize_call_int(JavaThread* thread, int value))
610   deopt_caller();
611   return (jint) value;
612 JRT_END
613 
614 
615 // private static JVMCIRuntime JVMCI.initializeRuntime()
616 JVM_ENTRY_NO_ENV(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
617   JNI_JVMCIENV(thread, env);
618   if (!EnableJVMCI) {
619     JVMCI_THROW_MSG_NULL(InternalError, "JVMCI is not enabled");
620   }
621   JVMCIENV->runtime()->initialize_HotSpotJVMCIRuntime(JVMCI_CHECK_NULL);
622   JVMCIObject runtime = JVMCIENV->runtime()->get_HotSpotJVMCIRuntime(JVMCI_CHECK_NULL);
623   return JVMCIENV->get_jobject(runtime);
624 JVM_END
625 
call_getCompiler(TRAPS)626 void JVMCIRuntime::call_getCompiler(TRAPS) {
627   THREAD_JVMCIENV(JavaThread::current());
628   JVMCIObject jvmciRuntime = JVMCIRuntime::get_HotSpotJVMCIRuntime(JVMCI_CHECK);
629   initialize(JVMCIENV);
630   JVMCIENV->call_HotSpotJVMCIRuntime_getCompiler(jvmciRuntime, JVMCI_CHECK);
631 }
632 
initialize(int nmethod_mirror_index,const char * name,FailedSpeculation ** failed_speculations)633 void JVMCINMethodData::initialize(
634   int nmethod_mirror_index,
635   const char* name,
636   FailedSpeculation** failed_speculations)
637 {
638   _failed_speculations = failed_speculations;
639   _nmethod_mirror_index = nmethod_mirror_index;
640   if (name != NULL) {
641     _has_name = true;
642     char* dest = (char*) this->name();
643     strcpy(dest, name);
644   } else {
645     _has_name = false;
646   }
647 }
648 
add_failed_speculation(nmethod * nm,jlong speculation)649 void JVMCINMethodData::add_failed_speculation(nmethod* nm, jlong speculation) {
650   jlong index = speculation >> JVMCINMethodData::SPECULATION_LENGTH_BITS;
651   guarantee(index >= 0 && index <= max_jint, "Encoded JVMCI speculation index is not a positive Java int: " INTPTR_FORMAT, index);
652   int length = speculation & JVMCINMethodData::SPECULATION_LENGTH_MASK;
653   if (index + length > (uint) nm->speculations_size()) {
654     fatal(INTPTR_FORMAT "[index: " JLONG_FORMAT ", length: %d out of bounds wrt encoded speculations of length %u", speculation, index, length, nm->speculations_size());
655   }
656   address data = nm->speculations_begin() + index;
657   FailedSpeculation::add_failed_speculation(nm, _failed_speculations, data, length);
658 }
659 
get_nmethod_mirror(nmethod * nm,bool phantom_ref)660 oop JVMCINMethodData::get_nmethod_mirror(nmethod* nm, bool phantom_ref) {
661   if (_nmethod_mirror_index == -1) {
662     return NULL;
663   }
664   if (phantom_ref) {
665     return nm->oop_at_phantom(_nmethod_mirror_index);
666   } else {
667     return nm->oop_at(_nmethod_mirror_index);
668   }
669 }
670 
set_nmethod_mirror(nmethod * nm,oop new_mirror)671 void JVMCINMethodData::set_nmethod_mirror(nmethod* nm, oop new_mirror) {
672   assert(_nmethod_mirror_index != -1, "cannot set JVMCI mirror for nmethod");
673   oop* addr = nm->oop_addr_at(_nmethod_mirror_index);
674   assert(new_mirror != NULL, "use clear_nmethod_mirror to clear the mirror");
675   assert(*addr == NULL, "cannot overwrite non-null mirror");
676 
677   *addr = new_mirror;
678 
679   // Since we've patched some oops in the nmethod,
680   // (re)register it with the heap.
681   MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
682   Universe::heap()->register_nmethod(nm);
683 }
684 
clear_nmethod_mirror(nmethod * nm)685 void JVMCINMethodData::clear_nmethod_mirror(nmethod* nm) {
686   if (_nmethod_mirror_index != -1) {
687     oop* addr = nm->oop_addr_at(_nmethod_mirror_index);
688     *addr = NULL;
689   }
690 }
691 
invalidate_nmethod_mirror(nmethod * nm)692 void JVMCINMethodData::invalidate_nmethod_mirror(nmethod* nm) {
693   oop nmethod_mirror = get_nmethod_mirror(nm, /* phantom_ref */ false);
694   if (nmethod_mirror == NULL) {
695     return;
696   }
697 
698   // Update the values in the mirror if it still refers to nm.
699   // We cannot use JVMCIObject to wrap the mirror as this is called
700   // during GC, forbidding the creation of JNIHandles.
701   JVMCIEnv* jvmciEnv = NULL;
702   nmethod* current = (nmethod*) HotSpotJVMCI::InstalledCode::address(jvmciEnv, nmethod_mirror);
703   if (nm == current) {
704     if (!nm->is_alive()) {
705       // Break the link from the mirror to nm such that
706       // future invocations via the mirror will result in
707       // an InvalidInstalledCodeException.
708       HotSpotJVMCI::InstalledCode::set_address(jvmciEnv, nmethod_mirror, 0);
709       HotSpotJVMCI::InstalledCode::set_entryPoint(jvmciEnv, nmethod_mirror, 0);
710     } else if (nm->is_not_entrant()) {
711       // Zero the entry point so any new invocation will fail but keep
712       // the address link around that so that existing activations can
713       // be deoptimized via the mirror (i.e. JVMCIEnv::invalidate_installed_code).
714       HotSpotJVMCI::InstalledCode::set_entryPoint(jvmciEnv, nmethod_mirror, 0);
715     }
716   }
717 
718   if (_nmethod_mirror_index != -1 && nm->is_unloaded()) {
719     // Drop the reference to the nmethod mirror object but don't clear the actual oop reference.  Otherwise
720     // it would appear that the nmethod didn't need to be unloaded in the first place.
721     _nmethod_mirror_index = -1;
722   }
723 }
724 
JVMCIRuntime(int id)725 JVMCIRuntime::JVMCIRuntime(int id) {
726   _init_state = uninitialized;
727   _shared_library_javavm = NULL;
728   _id = id;
729   _metadata_handles = new MetadataHandles();
730   JVMCI_event_1("created new JVMCI runtime %d (" PTR_FORMAT ")", id, p2i(this));
731 }
732 
733 // Handles to objects in the Hotspot heap.
object_handles()734 static OopStorage* object_handles() {
735   return Universe::vm_global();
736 }
737 
make_global(const Handle & obj)738 jobject JVMCIRuntime::make_global(const Handle& obj) {
739   assert(!Universe::heap()->is_gc_active(), "can't extend the root set during GC");
740   assert(oopDesc::is_oop(obj()), "not an oop");
741   oop* ptr = object_handles()->allocate();
742   jobject res = NULL;
743   if (ptr != NULL) {
744     assert(*ptr == NULL, "invariant");
745     NativeAccess<>::oop_store(ptr, obj());
746     res = reinterpret_cast<jobject>(ptr);
747   } else {
748     vm_exit_out_of_memory(sizeof(oop), OOM_MALLOC_ERROR,
749                           "Cannot create JVMCI oop handle");
750   }
751   MutexLocker ml(JVMCI_lock);
752   return res;
753 }
754 
destroy_global(jobject handle)755 void JVMCIRuntime::destroy_global(jobject handle) {
756   // Assert before nulling out, for better debugging.
757   assert(is_global_handle(handle), "precondition");
758   oop* oop_ptr = reinterpret_cast<oop*>(handle);
759   NativeAccess<>::oop_store(oop_ptr, (oop)NULL);
760   object_handles()->release(oop_ptr);
761   MutexLocker ml(JVMCI_lock);
762 }
763 
is_global_handle(jobject handle)764 bool JVMCIRuntime::is_global_handle(jobject handle) {
765   const oop* ptr = reinterpret_cast<oop*>(handle);
766   return object_handles()->allocation_status(ptr) == OopStorage::ALLOCATED_ENTRY;
767 }
768 
allocate_handle(const methodHandle & handle)769 jmetadata JVMCIRuntime::allocate_handle(const methodHandle& handle) {
770   MutexLocker ml(JVMCI_lock);
771   return _metadata_handles->allocate_handle(handle);
772 }
773 
allocate_handle(const constantPoolHandle & handle)774 jmetadata JVMCIRuntime::allocate_handle(const constantPoolHandle& handle) {
775   MutexLocker ml(JVMCI_lock);
776   return _metadata_handles->allocate_handle(handle);
777 }
778 
release_handle(jmetadata handle)779 void JVMCIRuntime::release_handle(jmetadata handle) {
780   MutexLocker ml(JVMCI_lock);
781   _metadata_handles->chain_free_list(handle);
782 }
783 
784 // Function for redirecting shared library JavaVM output to tty
_log(const char * buf,size_t count)785 static void _log(const char* buf, size_t count) {
786   tty->write((char*) buf, count);
787 }
788 
789 // Function for shared library JavaVM to flush tty
_flush_log()790 static void _flush_log() {
791   tty->flush();
792 }
793 
794 // Function for shared library JavaVM to exit HotSpot on a fatal error
_fatal()795 static void _fatal() {
796   fatal("Fatal error in JVMCI shared library");
797 }
798 
init_shared_library_javavm()799 JNIEnv* JVMCIRuntime::init_shared_library_javavm() {
800   JavaVM* javaVM = (JavaVM*) _shared_library_javavm;
801   if (javaVM == NULL) {
802     MutexLocker locker(JVMCI_lock);
803     // Check again under JVMCI_lock
804     javaVM = (JavaVM*) _shared_library_javavm;
805     if (javaVM != NULL) {
806       return NULL;
807     }
808     char* sl_path;
809     void* sl_handle = JVMCI::get_shared_library(sl_path, true);
810 
811     jint (*JNI_CreateJavaVM)(JavaVM **pvm, void **penv, void *args);
812     typedef jint (*JNI_CreateJavaVM_t)(JavaVM **pvm, void **penv, void *args);
813 
814     JNI_CreateJavaVM = CAST_TO_FN_PTR(JNI_CreateJavaVM_t, os::dll_lookup(sl_handle, "JNI_CreateJavaVM"));
815     if (JNI_CreateJavaVM == NULL) {
816       fatal("Unable to find JNI_CreateJavaVM in %s", sl_path);
817     }
818 
819     ResourceMark rm;
820     JavaVMInitArgs vm_args;
821     vm_args.version = JNI_VERSION_1_2;
822     vm_args.ignoreUnrecognized = JNI_TRUE;
823     JavaVMOption options[4];
824     jlong javaVM_id = 0;
825 
826     // Protocol: JVMCI shared library JavaVM should support a non-standard "_javavm_id"
827     // option whose extraInfo info field is a pointer to which a unique id for the
828     // JavaVM should be written.
829     options[0].optionString = (char*) "_javavm_id";
830     options[0].extraInfo = &javaVM_id;
831 
832     options[1].optionString = (char*) "_log";
833     options[1].extraInfo = (void*) _log;
834     options[2].optionString = (char*) "_flush_log";
835     options[2].extraInfo = (void*) _flush_log;
836     options[3].optionString = (char*) "_fatal";
837     options[3].extraInfo = (void*) _fatal;
838 
839     vm_args.version = JNI_VERSION_1_2;
840     vm_args.options = options;
841     vm_args.nOptions = sizeof(options) / sizeof(JavaVMOption);
842 
843     JNIEnv* env = NULL;
844     int result = (*JNI_CreateJavaVM)(&javaVM, (void**) &env, &vm_args);
845     if (result == JNI_OK) {
846       guarantee(env != NULL, "missing env");
847       _shared_library_javavm = javaVM;
848       JVMCI_event_1("created JavaVM[%ld]@" PTR_FORMAT " for JVMCI runtime %d", javaVM_id, p2i(javaVM), _id);
849       return env;
850     } else {
851       fatal("JNI_CreateJavaVM failed with return value %d", result);
852     }
853   }
854   return NULL;
855 }
856 
init_JavaVM_info(jlongArray info,JVMCI_TRAPS)857 void JVMCIRuntime::init_JavaVM_info(jlongArray info, JVMCI_TRAPS) {
858   if (info != NULL) {
859     typeArrayOop info_oop = (typeArrayOop) JNIHandles::resolve(info);
860     if (info_oop->length() < 4) {
861       JVMCI_THROW_MSG(ArrayIndexOutOfBoundsException, err_msg("%d < 4", info_oop->length()));
862     }
863     JavaVM* javaVM = (JavaVM*) _shared_library_javavm;
864     info_oop->long_at_put(0, (jlong) (address) javaVM);
865     info_oop->long_at_put(1, (jlong) (address) javaVM->functions->reserved0);
866     info_oop->long_at_put(2, (jlong) (address) javaVM->functions->reserved1);
867     info_oop->long_at_put(3, (jlong) (address) javaVM->functions->reserved2);
868   }
869 }
870 
871 #define JAVAVM_CALL_BLOCK                                             \
872   guarantee(thread != NULL && _shared_library_javavm != NULL, "npe"); \
873   ThreadToNativeFromVM ttnfv(thread);                                 \
874   JavaVM* javavm = (JavaVM*) _shared_library_javavm;
875 
AttachCurrentThread(JavaThread * thread,void ** penv,void * args)876 jint JVMCIRuntime::AttachCurrentThread(JavaThread* thread, void **penv, void *args) {
877   JAVAVM_CALL_BLOCK
878   return javavm->AttachCurrentThread(penv, args);
879 }
880 
AttachCurrentThreadAsDaemon(JavaThread * thread,void ** penv,void * args)881 jint JVMCIRuntime::AttachCurrentThreadAsDaemon(JavaThread* thread, void **penv, void *args) {
882   JAVAVM_CALL_BLOCK
883   return javavm->AttachCurrentThreadAsDaemon(penv, args);
884 }
885 
DetachCurrentThread(JavaThread * thread)886 jint JVMCIRuntime::DetachCurrentThread(JavaThread* thread) {
887   JAVAVM_CALL_BLOCK
888   return javavm->DetachCurrentThread();
889 }
890 
GetEnv(JavaThread * thread,void ** penv,jint version)891 jint JVMCIRuntime::GetEnv(JavaThread* thread, void **penv, jint version) {
892   JAVAVM_CALL_BLOCK
893   return javavm->GetEnv(penv, version);
894 }
895 #undef JAVAVM_CALL_BLOCK                                             \
896 
initialize_HotSpotJVMCIRuntime(JVMCI_TRAPS)897 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(JVMCI_TRAPS) {
898   if (is_HotSpotJVMCIRuntime_initialized()) {
899     if (JVMCIENV->is_hotspot() && UseJVMCINativeLibrary) {
900       JVMCI_THROW_MSG(InternalError, "JVMCI has already been enabled in the JVMCI shared library");
901     }
902   }
903 
904   initialize(JVMCIENV);
905 
906   // This should only be called in the context of the JVMCI class being initialized
907   JVMCIObject result = JVMCIENV->call_HotSpotJVMCIRuntime_runtime(JVMCI_CHECK);
908   result = JVMCIENV->make_global(result);
909 
910   OrderAccess::storestore();  // Ensure handle is fully constructed before publishing
911   _HotSpotJVMCIRuntime_instance = result;
912 
913   JVMCI::_is_initialized = true;
914 }
915 
initialize(JVMCIEnv * JVMCIENV)916 void JVMCIRuntime::initialize(JVMCIEnv* JVMCIENV) {
917   // Check first without JVMCI_lock
918   if (_init_state == fully_initialized) {
919     return;
920   }
921 
922   MutexLocker locker(JVMCI_lock);
923   // Check again under JVMCI_lock
924   if (_init_state == fully_initialized) {
925     return;
926   }
927 
928   while (_init_state == being_initialized) {
929     JVMCI_event_1("waiting for initialization of JVMCI runtime %d", _id);
930     JVMCI_lock->wait();
931     if (_init_state == fully_initialized) {
932       JVMCI_event_1("done waiting for initialization of JVMCI runtime %d", _id);
933       return;
934     }
935   }
936 
937   JVMCI_event_1("initializing JVMCI runtime %d", _id);
938   _init_state = being_initialized;
939 
940   {
941     MutexUnlocker unlock(JVMCI_lock);
942 
943     JavaThread* THREAD = JavaThread::current();
944     HandleMark hm(THREAD);
945     ResourceMark rm(THREAD);
946     if (JVMCIENV->is_hotspot()) {
947       HotSpotJVMCI::compute_offsets(CHECK_EXIT);
948     } else {
949       JNIAccessMark jni(JVMCIENV);
950 
951       JNIJVMCI::initialize_ids(jni.env());
952       if (jni()->ExceptionCheck()) {
953         jni()->ExceptionDescribe();
954         fatal("JNI exception during init");
955       }
956     }
957 
958     if (!JVMCIENV->is_hotspot()) {
959       JNIAccessMark jni(JVMCIENV, THREAD);
960       JNIJVMCI::register_natives(jni.env());
961     }
962     create_jvmci_primitive_type(T_BOOLEAN, JVMCI_CHECK_EXIT_((void)0));
963     create_jvmci_primitive_type(T_BYTE, JVMCI_CHECK_EXIT_((void)0));
964     create_jvmci_primitive_type(T_CHAR, JVMCI_CHECK_EXIT_((void)0));
965     create_jvmci_primitive_type(T_SHORT, JVMCI_CHECK_EXIT_((void)0));
966     create_jvmci_primitive_type(T_INT, JVMCI_CHECK_EXIT_((void)0));
967     create_jvmci_primitive_type(T_LONG, JVMCI_CHECK_EXIT_((void)0));
968     create_jvmci_primitive_type(T_FLOAT, JVMCI_CHECK_EXIT_((void)0));
969     create_jvmci_primitive_type(T_DOUBLE, JVMCI_CHECK_EXIT_((void)0));
970     create_jvmci_primitive_type(T_VOID, JVMCI_CHECK_EXIT_((void)0));
971 
972     if (!JVMCIENV->is_hotspot()) {
973       JVMCIENV->copy_saved_properties();
974     }
975   }
976 
977   _init_state = fully_initialized;
978   JVMCI_event_1("initialized JVMCI runtime %d", _id);
979   JVMCI_lock->notify_all();
980 }
981 
create_jvmci_primitive_type(BasicType type,JVMCI_TRAPS)982 JVMCIObject JVMCIRuntime::create_jvmci_primitive_type(BasicType type, JVMCI_TRAPS) {
983   Thread* THREAD = Thread::current();
984   // These primitive types are long lived and are created before the runtime is fully set up
985   // so skip registering them for scanning.
986   JVMCIObject mirror = JVMCIENV->get_object_constant(java_lang_Class::primitive_mirror(type), false, true);
987   if (JVMCIENV->is_hotspot()) {
988     JavaValue result(T_OBJECT);
989     JavaCallArguments args;
990     args.push_oop(Handle(THREAD, HotSpotJVMCI::resolve(mirror)));
991     args.push_int(type2char(type));
992     JavaCalls::call_static(&result, HotSpotJVMCI::HotSpotResolvedPrimitiveType::klass(), vmSymbols::fromMetaspace_name(), vmSymbols::primitive_fromMetaspace_signature(), &args, CHECK_(JVMCIObject()));
993 
994     return JVMCIENV->wrap(JNIHandles::make_local((oop)result.get_jobject()));
995   } else {
996     JNIAccessMark jni(JVMCIENV);
997     jobject result = jni()->CallStaticObjectMethod(JNIJVMCI::HotSpotResolvedPrimitiveType::clazz(),
998                                            JNIJVMCI::HotSpotResolvedPrimitiveType_fromMetaspace_method(),
999                                            mirror.as_jobject(), type2char(type));
1000     if (jni()->ExceptionCheck()) {
1001       return JVMCIObject();
1002     }
1003     return JVMCIENV->wrap(result);
1004   }
1005 }
1006 
initialize_JVMCI(JVMCI_TRAPS)1007 void JVMCIRuntime::initialize_JVMCI(JVMCI_TRAPS) {
1008   if (!is_HotSpotJVMCIRuntime_initialized()) {
1009     initialize(JVMCI_CHECK);
1010     JVMCIENV->call_JVMCI_getRuntime(JVMCI_CHECK);
1011   }
1012 }
1013 
get_HotSpotJVMCIRuntime(JVMCI_TRAPS)1014 JVMCIObject JVMCIRuntime::get_HotSpotJVMCIRuntime(JVMCI_TRAPS) {
1015   initialize(JVMCIENV);
1016   initialize_JVMCI(JVMCI_CHECK_(JVMCIObject()));
1017   return _HotSpotJVMCIRuntime_instance;
1018 }
1019 
1020 // private static void CompilerToVM.registerNatives()
1021 JVM_ENTRY_NO_ENV(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
1022   JNI_JVMCIENV(thread, env);
1023 
1024   if (!EnableJVMCI) {
1025     JVMCI_THROW_MSG(InternalError, "JVMCI is not enabled");
1026   }
1027 
1028   JVMCIENV->runtime()->initialize(JVMCIENV);
1029 
1030   {
1031     ResourceMark rm(thread);
1032     HandleMark hm(thread);
1033     ThreadToNativeFromVM trans(thread);
1034 
1035     // Ensure _non_oop_bits is initialized
1036     Universe::non_oop_word();
1037 
1038     if (JNI_OK != env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count())) {
1039       if (!env->ExceptionCheck()) {
1040         for (int i = 0; i < CompilerToVM::methods_count(); i++) {
1041           if (JNI_OK != env->RegisterNatives(c2vmClass, CompilerToVM::methods + i, 1)) {
1042             guarantee(false, "Error registering JNI method %s%s", CompilerToVM::methods[i].name, CompilerToVM::methods[i].signature);
1043             break;
1044           }
1045         }
1046       } else {
1047         env->ExceptionDescribe();
1048       }
1049       guarantee(false, "Failed registering CompilerToVM native methods");
1050     }
1051   }
1052 JVM_END
1053 
1054 
shutdown()1055 void JVMCIRuntime::shutdown() {
1056   if (_HotSpotJVMCIRuntime_instance.is_non_null()) {
1057     JVMCI_event_1("shutting down HotSpotJVMCIRuntime for JVMCI runtime %d", _id);
1058     JVMCIEnv __stack_jvmci_env__(JavaThread::current(), _HotSpotJVMCIRuntime_instance.is_hotspot(), __FILE__, __LINE__);
1059     JVMCIEnv* JVMCIENV = &__stack_jvmci_env__;
1060     JVMCIENV->call_HotSpotJVMCIRuntime_shutdown(_HotSpotJVMCIRuntime_instance);
1061     JVMCI_event_1("shut down HotSpotJVMCIRuntime for JVMCI runtime %d", _id);
1062   }
1063 }
1064 
bootstrap_finished(TRAPS)1065 void JVMCIRuntime::bootstrap_finished(TRAPS) {
1066   if (_HotSpotJVMCIRuntime_instance.is_non_null()) {
1067     THREAD_JVMCIENV(JavaThread::current());
1068     JVMCIENV->call_HotSpotJVMCIRuntime_bootstrapFinished(_HotSpotJVMCIRuntime_instance, JVMCIENV);
1069   }
1070 }
1071 
describe_pending_hotspot_exception(JavaThread * THREAD,bool clear)1072 void JVMCIRuntime::describe_pending_hotspot_exception(JavaThread* THREAD, bool clear) {
1073   if (HAS_PENDING_EXCEPTION) {
1074     Handle exception(THREAD, PENDING_EXCEPTION);
1075     const char* exception_file = THREAD->exception_file();
1076     int exception_line = THREAD->exception_line();
1077     CLEAR_PENDING_EXCEPTION;
1078     if (exception->is_a(SystemDictionary::ThreadDeath_klass())) {
1079       // Don't print anything if we are being killed.
1080     } else {
1081       java_lang_Throwable::print_stack_trace(exception, tty);
1082 
1083       // Clear and ignore any exceptions raised during printing
1084       CLEAR_PENDING_EXCEPTION;
1085     }
1086     if (!clear) {
1087       THREAD->set_pending_exception(exception(), exception_file, exception_line);
1088     }
1089   }
1090 }
1091 
1092 
fatal_exception(JVMCIEnv * JVMCIENV,const char * message)1093 void JVMCIRuntime::fatal_exception(JVMCIEnv* JVMCIENV, const char* message) {
1094   JavaThread* THREAD = JavaThread::current();
1095 
1096   static volatile int report_error = 0;
1097   if (!report_error && Atomic::cmpxchg(&report_error, 0, 1) == 0) {
1098     // Only report an error once
1099     tty->print_raw_cr(message);
1100     if (JVMCIENV != NULL) {
1101       JVMCIENV->describe_pending_exception(true);
1102     } else {
1103       describe_pending_hotspot_exception(THREAD, true);
1104     }
1105   } else {
1106     // Allow error reporting thread to print the stack trace.
1107     THREAD->sleep(200);
1108   }
1109   fatal("Fatal exception in JVMCI: %s", message);
1110 }
1111 
1112 // ------------------------------------------------------------------
1113 // Note: the logic of this method should mirror the logic of
1114 // constantPoolOopDesc::verify_constant_pool_resolve.
check_klass_accessibility(Klass * accessing_klass,Klass * resolved_klass)1115 bool JVMCIRuntime::check_klass_accessibility(Klass* accessing_klass, Klass* resolved_klass) {
1116   if (accessing_klass->is_objArray_klass()) {
1117     accessing_klass = ObjArrayKlass::cast(accessing_klass)->bottom_klass();
1118   }
1119   if (!accessing_klass->is_instance_klass()) {
1120     return true;
1121   }
1122 
1123   if (resolved_klass->is_objArray_klass()) {
1124     // Find the element klass, if this is an array.
1125     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
1126   }
1127   if (resolved_klass->is_instance_klass()) {
1128     Reflection::VerifyClassAccessResults result =
1129       Reflection::verify_class_access(accessing_klass, InstanceKlass::cast(resolved_klass), true);
1130     return result == Reflection::ACCESS_OK;
1131   }
1132   return true;
1133 }
1134 
1135 // ------------------------------------------------------------------
get_klass_by_name_impl(Klass * & accessing_klass,const constantPoolHandle & cpool,Symbol * sym,bool require_local)1136 Klass* JVMCIRuntime::get_klass_by_name_impl(Klass*& accessing_klass,
1137                                           const constantPoolHandle& cpool,
1138                                           Symbol* sym,
1139                                           bool require_local) {
1140   JVMCI_EXCEPTION_CONTEXT;
1141 
1142   // Now we need to check the SystemDictionary
1143   if (sym->char_at(0) == JVM_SIGNATURE_CLASS &&
1144       sym->char_at(sym->utf8_length()-1) == JVM_SIGNATURE_ENDCLASS) {
1145     // This is a name from a signature.  Strip off the trimmings.
1146     // Call recursive to keep scope of strippedsym.
1147     TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1,
1148                                                         sym->utf8_length()-2);
1149     return get_klass_by_name_impl(accessing_klass, cpool, strippedsym, require_local);
1150   }
1151 
1152   Handle loader(THREAD, (oop)NULL);
1153   Handle domain(THREAD, (oop)NULL);
1154   if (accessing_klass != NULL) {
1155     loader = Handle(THREAD, accessing_klass->class_loader());
1156     domain = Handle(THREAD, accessing_klass->protection_domain());
1157   }
1158 
1159   Klass* found_klass;
1160   {
1161     ttyUnlocker ttyul;  // release tty lock to avoid ordering problems
1162     MutexLocker ml(Compile_lock);
1163     if (!require_local) {
1164       found_klass = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader, CHECK_NULL);
1165     } else {
1166       found_klass = SystemDictionary::find_instance_or_array_klass(sym, loader, domain, CHECK_NULL);
1167     }
1168   }
1169 
1170   // If we fail to find an array klass, look again for its element type.
1171   // The element type may be available either locally or via constraints.
1172   // In either case, if we can find the element type in the system dictionary,
1173   // we must build an array type around it.  The CI requires array klasses
1174   // to be loaded if their element klasses are loaded, except when memory
1175   // is exhausted.
1176   if (sym->char_at(0) == JVM_SIGNATURE_ARRAY &&
1177       (sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
1178     // We have an unloaded array.
1179     // Build it on the fly if the element class exists.
1180     TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1,
1181                                                      sym->utf8_length()-1);
1182 
1183     // Get element Klass recursively.
1184     Klass* elem_klass =
1185       get_klass_by_name_impl(accessing_klass,
1186                              cpool,
1187                              elem_sym,
1188                              require_local);
1189     if (elem_klass != NULL) {
1190       // Now make an array for it
1191       return elem_klass->array_klass(THREAD);
1192     }
1193   }
1194 
1195   if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {
1196     // Look inside the constant pool for pre-resolved class entries.
1197     for (int i = cpool->length() - 1; i >= 1; i--) {
1198       if (cpool->tag_at(i).is_klass()) {
1199         Klass*  kls = cpool->resolved_klass_at(i);
1200         if (kls->name() == sym) {
1201           return kls;
1202         }
1203       }
1204     }
1205   }
1206 
1207   return found_klass;
1208 }
1209 
1210 // ------------------------------------------------------------------
get_klass_by_name(Klass * accessing_klass,Symbol * klass_name,bool require_local)1211 Klass* JVMCIRuntime::get_klass_by_name(Klass* accessing_klass,
1212                                   Symbol* klass_name,
1213                                   bool require_local) {
1214   ResourceMark rm;
1215   constantPoolHandle cpool;
1216   return get_klass_by_name_impl(accessing_klass,
1217                                                  cpool,
1218                                                  klass_name,
1219                                                  require_local);
1220 }
1221 
1222 // ------------------------------------------------------------------
1223 // Implementation of get_klass_by_index.
get_klass_by_index_impl(const constantPoolHandle & cpool,int index,bool & is_accessible,Klass * accessor)1224 Klass* JVMCIRuntime::get_klass_by_index_impl(const constantPoolHandle& cpool,
1225                                         int index,
1226                                         bool& is_accessible,
1227                                         Klass* accessor) {
1228   JVMCI_EXCEPTION_CONTEXT;
1229   Klass* klass = ConstantPool::klass_at_if_loaded(cpool, index);
1230   Symbol* klass_name = NULL;
1231   if (klass == NULL) {
1232     klass_name = cpool->klass_name_at(index);
1233   }
1234 
1235   if (klass == NULL) {
1236     // Not found in constant pool.  Use the name to do the lookup.
1237     Klass* k = get_klass_by_name_impl(accessor,
1238                                         cpool,
1239                                         klass_name,
1240                                         false);
1241     // Calculate accessibility the hard way.
1242     if (k == NULL) {
1243       is_accessible = false;
1244     } else if (k->class_loader() != accessor->class_loader() &&
1245                get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {
1246       // Loaded only remotely.  Not linked yet.
1247       is_accessible = false;
1248     } else {
1249       // Linked locally, and we must also check public/private, etc.
1250       is_accessible = check_klass_accessibility(accessor, k);
1251     }
1252     if (!is_accessible) {
1253       return NULL;
1254     }
1255     return k;
1256   }
1257 
1258   // It is known to be accessible, since it was found in the constant pool.
1259   is_accessible = true;
1260   return klass;
1261 }
1262 
1263 // ------------------------------------------------------------------
1264 // Get a klass from the constant pool.
get_klass_by_index(const constantPoolHandle & cpool,int index,bool & is_accessible,Klass * accessor)1265 Klass* JVMCIRuntime::get_klass_by_index(const constantPoolHandle& cpool,
1266                                    int index,
1267                                    bool& is_accessible,
1268                                    Klass* accessor) {
1269   ResourceMark rm;
1270   Klass* result = get_klass_by_index_impl(cpool, index, is_accessible, accessor);
1271   return result;
1272 }
1273 
1274 // ------------------------------------------------------------------
1275 // Implementation of get_field_by_index.
1276 //
1277 // Implementation note: the results of field lookups are cached
1278 // in the accessor klass.
get_field_by_index_impl(InstanceKlass * klass,fieldDescriptor & field_desc,int index)1279 void JVMCIRuntime::get_field_by_index_impl(InstanceKlass* klass, fieldDescriptor& field_desc,
1280                                         int index) {
1281   JVMCI_EXCEPTION_CONTEXT;
1282 
1283   assert(klass->is_linked(), "must be linked before using its constant-pool");
1284 
1285   constantPoolHandle cpool(thread, klass->constants());
1286 
1287   // Get the field's name, signature, and type.
1288   Symbol* name  = cpool->name_ref_at(index);
1289 
1290   int nt_index = cpool->name_and_type_ref_index_at(index);
1291   int sig_index = cpool->signature_ref_index_at(nt_index);
1292   Symbol* signature = cpool->symbol_at(sig_index);
1293 
1294   // Get the field's declared holder.
1295   int holder_index = cpool->klass_ref_index_at(index);
1296   bool holder_is_accessible;
1297   Klass* declared_holder = get_klass_by_index(cpool, holder_index,
1298                                                holder_is_accessible,
1299                                                klass);
1300 
1301   // The declared holder of this field may not have been loaded.
1302   // Bail out with partial field information.
1303   if (!holder_is_accessible) {
1304     return;
1305   }
1306 
1307 
1308   // Perform the field lookup.
1309   Klass*  canonical_holder =
1310     InstanceKlass::cast(declared_holder)->find_field(name, signature, &field_desc);
1311   if (canonical_holder == NULL) {
1312     return;
1313   }
1314 
1315   assert(canonical_holder == field_desc.field_holder(), "just checking");
1316 }
1317 
1318 // ------------------------------------------------------------------
1319 // Get a field by index from a klass's constant pool.
get_field_by_index(InstanceKlass * accessor,fieldDescriptor & fd,int index)1320 void JVMCIRuntime::get_field_by_index(InstanceKlass* accessor, fieldDescriptor& fd, int index) {
1321   ResourceMark rm;
1322   return get_field_by_index_impl(accessor, fd, index);
1323 }
1324 
1325 // ------------------------------------------------------------------
1326 // Perform an appropriate method lookup based on accessor, holder,
1327 // name, signature, and bytecode.
lookup_method(InstanceKlass * accessor,Klass * holder,Symbol * name,Symbol * sig,Bytecodes::Code bc,constantTag tag)1328 Method* JVMCIRuntime::lookup_method(InstanceKlass* accessor,
1329                                     Klass*        holder,
1330                                     Symbol*       name,
1331                                     Symbol*       sig,
1332                                     Bytecodes::Code bc,
1333                                     constantTag   tag) {
1334   // Accessibility checks are performed in JVMCIEnv::get_method_by_index_impl().
1335   assert(check_klass_accessibility(accessor, holder), "holder not accessible");
1336 
1337   LinkInfo link_info(holder, name, sig, accessor,
1338                      LinkInfo::AccessCheck::required,
1339                      LinkInfo::LoaderConstraintCheck::required,
1340                      tag);
1341   switch (bc) {
1342     case Bytecodes::_invokestatic:
1343       return LinkResolver::resolve_static_call_or_null(link_info);
1344     case Bytecodes::_invokespecial:
1345       return LinkResolver::resolve_special_call_or_null(link_info);
1346     case Bytecodes::_invokeinterface:
1347       return LinkResolver::linktime_resolve_interface_method_or_null(link_info);
1348     case Bytecodes::_invokevirtual:
1349       return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
1350     default:
1351       fatal("Unhandled bytecode: %s", Bytecodes::name(bc));
1352       return NULL; // silence compiler warnings
1353   }
1354 }
1355 
1356 
1357 // ------------------------------------------------------------------
get_method_by_index_impl(const constantPoolHandle & cpool,int index,Bytecodes::Code bc,InstanceKlass * accessor)1358 Method* JVMCIRuntime::get_method_by_index_impl(const constantPoolHandle& cpool,
1359                                                int index, Bytecodes::Code bc,
1360                                                InstanceKlass* accessor) {
1361   if (bc == Bytecodes::_invokedynamic) {
1362     ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);
1363     bool is_resolved = !cpce->is_f1_null();
1364     if (is_resolved) {
1365       // Get the invoker Method* from the constant pool.
1366       // (The appendix argument, if any, will be noted in the method's signature.)
1367       Method* adapter = cpce->f1_as_method();
1368       return adapter;
1369     }
1370 
1371     return NULL;
1372   }
1373 
1374   int holder_index = cpool->klass_ref_index_at(index);
1375   bool holder_is_accessible;
1376   Klass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
1377 
1378   // Get the method's name and signature.
1379   Symbol* name_sym = cpool->name_ref_at(index);
1380   Symbol* sig_sym  = cpool->signature_ref_at(index);
1381 
1382   if (cpool->has_preresolution()
1383       || ((holder == SystemDictionary::MethodHandle_klass() || holder == SystemDictionary::VarHandle_klass()) &&
1384           MethodHandles::is_signature_polymorphic_name(holder, name_sym))) {
1385     // Short-circuit lookups for JSR 292-related call sites.
1386     // That is, do not rely only on name-based lookups, because they may fail
1387     // if the names are not resolvable in the boot class loader (7056328).
1388     switch (bc) {
1389     case Bytecodes::_invokevirtual:
1390     case Bytecodes::_invokeinterface:
1391     case Bytecodes::_invokespecial:
1392     case Bytecodes::_invokestatic:
1393       {
1394         Method* m = ConstantPool::method_at_if_loaded(cpool, index);
1395         if (m != NULL) {
1396           return m;
1397         }
1398       }
1399       break;
1400     default:
1401       break;
1402     }
1403   }
1404 
1405   if (holder_is_accessible) { // Our declared holder is loaded.
1406     constantTag tag = cpool->tag_ref_at(index);
1407     Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
1408     if (m != NULL) {
1409       // We found the method.
1410       return m;
1411     }
1412   }
1413 
1414   // Either the declared holder was not loaded, or the method could
1415   // not be found.
1416 
1417   return NULL;
1418 }
1419 
1420 // ------------------------------------------------------------------
get_instance_klass_for_declared_method_holder(Klass * method_holder)1421 InstanceKlass* JVMCIRuntime::get_instance_klass_for_declared_method_holder(Klass* method_holder) {
1422   // For the case of <array>.clone(), the method holder can be an ArrayKlass*
1423   // instead of an InstanceKlass*.  For that case simply pretend that the
1424   // declared holder is Object.clone since that's where the call will bottom out.
1425   if (method_holder->is_instance_klass()) {
1426     return InstanceKlass::cast(method_holder);
1427   } else if (method_holder->is_array_klass()) {
1428     return SystemDictionary::Object_klass();
1429   } else {
1430     ShouldNotReachHere();
1431   }
1432   return NULL;
1433 }
1434 
1435 
1436 // ------------------------------------------------------------------
get_method_by_index(const constantPoolHandle & cpool,int index,Bytecodes::Code bc,InstanceKlass * accessor)1437 Method* JVMCIRuntime::get_method_by_index(const constantPoolHandle& cpool,
1438                                      int index, Bytecodes::Code bc,
1439                                      InstanceKlass* accessor) {
1440   ResourceMark rm;
1441   return get_method_by_index_impl(cpool, index, bc, accessor);
1442 }
1443 
1444 // ------------------------------------------------------------------
1445 // Check for changes to the system dictionary during compilation
1446 // class loads, evolution, breakpoints
validate_compile_task_dependencies(Dependencies * dependencies,JVMCICompileState * compile_state,char ** failure_detail)1447 JVMCI::CodeInstallResult JVMCIRuntime::validate_compile_task_dependencies(Dependencies* dependencies, JVMCICompileState* compile_state, char** failure_detail) {
1448   // If JVMTI capabilities were enabled during compile, the compilation is invalidated.
1449   if (compile_state != NULL && compile_state->jvmti_state_changed()) {
1450     *failure_detail = (char*) "Jvmti state change during compilation invalidated dependencies";
1451     return JVMCI::dependencies_failed;
1452   }
1453 
1454   CompileTask* task = compile_state == NULL ? NULL : compile_state->task();
1455   Dependencies::DepType result = dependencies->validate_dependencies(task, failure_detail);
1456   if (result == Dependencies::end_marker) {
1457     return JVMCI::ok;
1458   }
1459 
1460   return JVMCI::dependencies_failed;
1461 }
1462 
compile_method(JVMCIEnv * JVMCIENV,JVMCICompiler * compiler,const methodHandle & method,int entry_bci)1463 void JVMCIRuntime::compile_method(JVMCIEnv* JVMCIENV, JVMCICompiler* compiler, const methodHandle& method, int entry_bci) {
1464   JVMCI_EXCEPTION_CONTEXT
1465 
1466   JVMCICompileState* compile_state = JVMCIENV->compile_state();
1467 
1468   bool is_osr = entry_bci != InvocationEntryBci;
1469   if (compiler->is_bootstrapping() && is_osr) {
1470     // no OSR compilations during bootstrap - the compiler is just too slow at this point,
1471     // and we know that there are no endless loops
1472     compile_state->set_failure(true, "No OSR during bootstrap");
1473     return;
1474   }
1475   if (JVMCI::in_shutdown()) {
1476     compile_state->set_failure(false, "Avoiding compilation during shutdown");
1477     return;
1478   }
1479 
1480   HandleMark hm(thread);
1481   JVMCIObject receiver = get_HotSpotJVMCIRuntime(JVMCIENV);
1482   if (JVMCIENV->has_pending_exception()) {
1483     fatal_exception(JVMCIENV, "Exception during HotSpotJVMCIRuntime initialization");
1484   }
1485   JVMCIObject jvmci_method = JVMCIENV->get_jvmci_method(method, JVMCIENV);
1486   if (JVMCIENV->has_pending_exception()) {
1487     JVMCIENV->describe_pending_exception(true);
1488     compile_state->set_failure(false, "exception getting JVMCI wrapper method");
1489     return;
1490   }
1491 
1492   JVMCIObject result_object = JVMCIENV->call_HotSpotJVMCIRuntime_compileMethod(receiver, jvmci_method, entry_bci,
1493                                                                      (jlong) compile_state, compile_state->task()->compile_id());
1494   if (!JVMCIENV->has_pending_exception()) {
1495     if (result_object.is_non_null()) {
1496       JVMCIObject failure_message = JVMCIENV->get_HotSpotCompilationRequestResult_failureMessage(result_object);
1497       if (failure_message.is_non_null()) {
1498         // Copy failure reason into resource memory first ...
1499         const char* failure_reason = JVMCIENV->as_utf8_string(failure_message);
1500         // ... and then into the C heap.
1501         failure_reason = os::strdup(failure_reason, mtJVMCI);
1502         bool retryable = JVMCIENV->get_HotSpotCompilationRequestResult_retry(result_object) != 0;
1503         compile_state->set_failure(retryable, failure_reason, true);
1504       } else {
1505         if (compile_state->task()->code() == NULL) {
1506           compile_state->set_failure(true, "no nmethod produced");
1507         } else {
1508           compile_state->task()->set_num_inlined_bytecodes(JVMCIENV->get_HotSpotCompilationRequestResult_inlinedBytecodes(result_object));
1509           compiler->inc_methods_compiled();
1510         }
1511       }
1512     } else {
1513       assert(false, "JVMCICompiler.compileMethod should always return non-null");
1514     }
1515   } else {
1516     // An uncaught exception here implies failure during compiler initialization.
1517     // The only sensible thing to do here is to exit the VM.
1518     fatal_exception(JVMCIENV, "Exception during JVMCI compiler initialization");
1519   }
1520   if (compiler->is_bootstrapping()) {
1521     compiler->set_bootstrap_compilation_request_handled();
1522   }
1523 }
1524 
is_gc_supported(JVMCIEnv * JVMCIENV,CollectedHeap::Name name)1525 bool JVMCIRuntime::is_gc_supported(JVMCIEnv* JVMCIENV, CollectedHeap::Name name) {
1526   JVMCI_EXCEPTION_CONTEXT
1527 
1528   JVMCIObject receiver = get_HotSpotJVMCIRuntime(JVMCIENV);
1529   if (JVMCIENV->has_pending_exception()) {
1530     fatal_exception(JVMCIENV, "Exception during HotSpotJVMCIRuntime initialization");
1531   }
1532   return JVMCIENV->call_HotSpotJVMCIRuntime_isGCSupported(receiver, (int) name);
1533 }
1534 
1535 // ------------------------------------------------------------------
register_method(JVMCIEnv * JVMCIENV,const methodHandle & method,nmethod * & nm,int entry_bci,CodeOffsets * offsets,int orig_pc_offset,CodeBuffer * code_buffer,int frame_words,OopMapSet * oop_map_set,ExceptionHandlerTable * handler_table,ImplicitExceptionTable * implicit_exception_table,AbstractCompiler * compiler,DebugInformationRecorder * debug_info,Dependencies * dependencies,int compile_id,bool has_unsafe_access,bool has_wide_vector,JVMCIObject compiled_code,JVMCIObject nmethod_mirror,FailedSpeculation ** failed_speculations,char * speculations,int speculations_len)1536 JVMCI::CodeInstallResult JVMCIRuntime::register_method(JVMCIEnv* JVMCIENV,
1537                                 const methodHandle& method,
1538                                 nmethod*& nm,
1539                                 int entry_bci,
1540                                 CodeOffsets* offsets,
1541                                 int orig_pc_offset,
1542                                 CodeBuffer* code_buffer,
1543                                 int frame_words,
1544                                 OopMapSet* oop_map_set,
1545                                 ExceptionHandlerTable* handler_table,
1546                                 ImplicitExceptionTable* implicit_exception_table,
1547                                 AbstractCompiler* compiler,
1548                                 DebugInformationRecorder* debug_info,
1549                                 Dependencies* dependencies,
1550                                 int compile_id,
1551                                 bool has_unsafe_access,
1552                                 bool has_wide_vector,
1553                                 JVMCIObject compiled_code,
1554                                 JVMCIObject nmethod_mirror,
1555                                 FailedSpeculation** failed_speculations,
1556                                 char* speculations,
1557                                 int speculations_len) {
1558   JVMCI_EXCEPTION_CONTEXT;
1559   nm = NULL;
1560   int comp_level = CompLevel_full_optimization;
1561   char* failure_detail = NULL;
1562 
1563   bool install_default = JVMCIENV->get_HotSpotNmethod_isDefault(nmethod_mirror) != 0;
1564   assert(JVMCIENV->isa_HotSpotNmethod(nmethod_mirror), "must be");
1565   JVMCIObject name = JVMCIENV->get_InstalledCode_name(nmethod_mirror);
1566   const char* nmethod_mirror_name = name.is_null() ? NULL : JVMCIENV->as_utf8_string(name);
1567   int nmethod_mirror_index;
1568   if (!install_default) {
1569     // Reserve or initialize mirror slot in the oops table.
1570     OopRecorder* oop_recorder = debug_info->oop_recorder();
1571     nmethod_mirror_index = oop_recorder->allocate_oop_index(nmethod_mirror.is_hotspot() ? nmethod_mirror.as_jobject() : NULL);
1572   } else {
1573     // A default HotSpotNmethod mirror is never tracked by the nmethod
1574     nmethod_mirror_index = -1;
1575   }
1576 
1577   JVMCI::CodeInstallResult result(JVMCI::ok);
1578 
1579   // We require method counters to store some method state (max compilation levels) required by the compilation policy.
1580   if (method->get_method_counters(THREAD) == NULL) {
1581     result = JVMCI::cache_full;
1582     failure_detail = (char*) "can't create method counters";
1583   }
1584 
1585   if (result == JVMCI::ok) {
1586     // To prevent compile queue updates.
1587     MutexLocker locker(THREAD, MethodCompileQueue_lock);
1588 
1589     // Prevent SystemDictionary::add_to_hierarchy from running
1590     // and invalidating our dependencies until we install this method.
1591     MutexLocker ml(Compile_lock);
1592 
1593     // Encode the dependencies now, so we can check them right away.
1594     dependencies->encode_content_bytes();
1595 
1596     // Record the dependencies for the current compile in the log
1597     if (LogCompilation) {
1598       for (Dependencies::DepStream deps(dependencies); deps.next(); ) {
1599         deps.log_dependency();
1600       }
1601     }
1602 
1603     // Check for {class loads, evolution, breakpoints} during compilation
1604     result = validate_compile_task_dependencies(dependencies, JVMCIENV->compile_state(), &failure_detail);
1605     if (result != JVMCI::ok) {
1606       // While not a true deoptimization, it is a preemptive decompile.
1607       MethodData* mdp = method()->method_data();
1608       if (mdp != NULL) {
1609         mdp->inc_decompile_count();
1610 #ifdef ASSERT
1611         if (mdp->decompile_count() > (uint)PerMethodRecompilationCutoff) {
1612           ResourceMark m;
1613           tty->print_cr("WARN: endless recompilation of %s. Method was set to not compilable.", method()->name_and_sig_as_C_string());
1614         }
1615 #endif
1616       }
1617 
1618       // All buffers in the CodeBuffer are allocated in the CodeCache.
1619       // If the code buffer is created on each compile attempt
1620       // as in C2, then it must be freed.
1621       //code_buffer->free_blob();
1622     } else {
1623       nm =  nmethod::new_nmethod(method,
1624                                  compile_id,
1625                                  entry_bci,
1626                                  offsets,
1627                                  orig_pc_offset,
1628                                  debug_info, dependencies, code_buffer,
1629                                  frame_words, oop_map_set,
1630                                  handler_table, implicit_exception_table,
1631                                  compiler, comp_level, GrowableArrayView<BufferBlob*>::EMPTY,
1632                                  speculations, speculations_len,
1633                                  nmethod_mirror_index, nmethod_mirror_name, failed_speculations);
1634 
1635 
1636       // Free codeBlobs
1637       if (nm == NULL) {
1638         // The CodeCache is full.  Print out warning and disable compilation.
1639         {
1640           MutexUnlocker ml(Compile_lock);
1641           MutexUnlocker locker(MethodCompileQueue_lock);
1642           CompileBroker::handle_full_code_cache(CodeCache::get_code_blob_type(comp_level));
1643         }
1644       } else {
1645         nm->set_has_unsafe_access(has_unsafe_access);
1646         nm->set_has_wide_vectors(has_wide_vector);
1647 
1648         // Record successful registration.
1649         // (Put nm into the task handle *before* publishing to the Java heap.)
1650         if (JVMCIENV->compile_state() != NULL) {
1651           JVMCIENV->compile_state()->task()->set_code(nm);
1652         }
1653 
1654         JVMCINMethodData* data = nm->jvmci_nmethod_data();
1655         assert(data != NULL, "must be");
1656         if (install_default) {
1657           assert(!nmethod_mirror.is_hotspot() || data->get_nmethod_mirror(nm, /* phantom_ref */ false) == NULL, "must be");
1658           if (entry_bci == InvocationEntryBci) {
1659             if (TieredCompilation) {
1660               // If there is an old version we're done with it
1661               CompiledMethod* old = method->code();
1662               if (TraceMethodReplacement && old != NULL) {
1663                 ResourceMark rm;
1664                 char *method_name = method->name_and_sig_as_C_string();
1665                 tty->print_cr("Replacing method %s", method_name);
1666               }
1667               if (old != NULL ) {
1668                 old->make_not_entrant();
1669               }
1670             }
1671 
1672             LogTarget(Info, nmethod, install) lt;
1673             if (lt.is_enabled()) {
1674               ResourceMark rm;
1675               char *method_name = method->name_and_sig_as_C_string();
1676               lt.print("Installing method (%d) %s [entry point: %p]",
1677                         comp_level, method_name, nm->entry_point());
1678             }
1679             // Allow the code to be executed
1680             MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1681             if (nm->make_in_use()) {
1682               method->set_code(method, nm);
1683             }
1684           } else {
1685             LogTarget(Info, nmethod, install) lt;
1686             if (lt.is_enabled()) {
1687               ResourceMark rm;
1688               char *method_name = method->name_and_sig_as_C_string();
1689               lt.print("Installing osr method (%d) %s @ %d",
1690                         comp_level, method_name, entry_bci);
1691             }
1692             MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1693             if (nm->make_in_use()) {
1694               InstanceKlass::cast(method->method_holder())->add_osr_nmethod(nm);
1695             }
1696           }
1697         } else {
1698           assert(!nmethod_mirror.is_hotspot() || data->get_nmethod_mirror(nm, /* phantom_ref */ false) == HotSpotJVMCI::resolve(nmethod_mirror), "must be");
1699         }
1700       }
1701       result = nm != NULL ? JVMCI::ok :JVMCI::cache_full;
1702     }
1703   }
1704 
1705   // String creation must be done outside lock
1706   if (failure_detail != NULL) {
1707     // A failure to allocate the string is silently ignored.
1708     JVMCIObject message = JVMCIENV->create_string(failure_detail, JVMCIENV);
1709     JVMCIENV->set_HotSpotCompiledNmethod_installationFailureMessage(compiled_code, message);
1710   }
1711 
1712   // JVMTI -- compiled method notification (must be done outside lock)
1713   if (nm != NULL) {
1714     nm->post_compiled_method_load_event();
1715   }
1716 
1717   return result;
1718 }
1719