1 
   2 
   3 /*
   4  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "jvm.h"
  29 #include "classfile/javaClasses.inline.hpp"
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/systemDictionary.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/debugInfoRec.hpp"
  34 #include "code/nmethod.hpp"
  35 #include "code/pcDesc.hpp"
  36 #include "code/scopeDesc.hpp"
  37 #include "compiler/compilationPolicy.hpp"
  38 #include "interpreter/bytecode.hpp"
  39 #include "interpreter/interpreter.hpp"
  40 #include "interpreter/oopMapCache.hpp"
  41 #include "memory/allocation.inline.hpp"
  42 #include "memory/oopFactory.hpp"
  43 #include "memory/resourceArea.hpp"
  44 #include "memory/universe.hpp"
  45 #include "oops/constantPool.hpp"
  46 #include "oops/method.hpp"
  47 #include "oops/objArrayKlass.hpp"
  48 #include "oops/objArrayOop.inline.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/fieldStreams.inline.hpp"
  51 #include "oops/typeArrayOop.inline.hpp"
  52 #include "oops/verifyOopClosure.hpp"
  53 #include "prims/jvmtiThreadState.hpp"
  54 #include "runtime/atomic.hpp"
  55 #include "runtime/biasedLocking.hpp"
  56 #include "runtime/deoptimization.hpp"
  57 #include "runtime/fieldDescriptor.hpp"
  58 #include "runtime/fieldDescriptor.inline.hpp"
  59 #include "runtime/frame.inline.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/interfaceSupport.inline.hpp"
  62 #include "runtime/jniHandles.inline.hpp"
  63 #include "runtime/objectMonitor.inline.hpp"
  64 #include "runtime/safepointVerifiers.hpp"
  65 #include "runtime/sharedRuntime.hpp"
  66 #include "runtime/signature.hpp"
  67 #include "runtime/stubRoutines.hpp"
  68 #include "runtime/thread.hpp"
  69 #include "runtime/threadSMR.hpp"
  70 #include "runtime/vframe.hpp"
  71 #include "runtime/vframeArray.hpp"
  72 #include "runtime/vframe_hp.hpp"
  73 #include "utilities/events.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/preserveException.hpp"
  76 #include "utilities/xmlstream.hpp"
  77 #if INCLUDE_JFR
  78 #include "jfr/jfrEvents.hpp"
  79 #include "jfr/metadata/jfrSerializer.hpp"
  80 #endif
  81 
  82 bool DeoptimizationMarker::_is_active = false;
  83 
  84 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
  85                                          int  caller_adjustment,
  86                                          int  caller_actual_parameters,
  87                                          int  number_of_frames,
  88                                          intptr_t* frame_sizes,
  89                                          address* frame_pcs,
  90                                          BasicType return_type,
  91                                          int exec_mode) {
  92   _size_of_deoptimized_frame = size_of_deoptimized_frame;
  93   _caller_adjustment         = caller_adjustment;
  94   _caller_actual_parameters  = caller_actual_parameters;
  95   _number_of_frames          = number_of_frames;
  96   _frame_sizes               = frame_sizes;
  97   _frame_pcs                 = frame_pcs;
  98   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
  99   _return_type               = return_type;
 100   _initial_info              = 0;
 101   // PD (x86 only)
 102   _counter_temp              = 0;
 103   _unpack_kind               = exec_mode;
 104   _sender_sp_temp            = 0;
 105 
 106   _total_frame_sizes         = size_of_frames();
 107   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 108 }
 109 
 110 
 111 Deoptimization::UnrollBlock::~UnrollBlock() {
 112   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
 113   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
 114   FREE_C_HEAP_ARRAY(intptr_t, _register_block);
 115 }
 116 
 117 
 118 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
 119   assert(register_number < RegisterMap::reg_count, "checking register number");
 120   return &_register_block[register_number * 2];
 121 }
 122 
 123 
 124 
 125 int Deoptimization::UnrollBlock::size_of_frames() const {
 126   // Acount first for the adjustment of the initial frame
 127   int result = _caller_adjustment;
 128   for (int index = 0; index < number_of_frames(); index++) {
 129     result += frame_sizes()[index];
 130   }
 131   return result;
 132 }
 133 
 134 
 135 void Deoptimization::UnrollBlock::print() {
 136   ttyLocker ttyl;
 137   tty->print_cr("UnrollBlock");
 138   tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 139   tty->print(   "  frame_sizes: ");
 140   for (int index = 0; index < number_of_frames(); index++) {
 141     tty->print(INTX_FORMAT " ", frame_sizes()[index]);
 142   }
 143   tty->cr();
 144 }
 145 
 146 
 147 // In order to make fetch_unroll_info work properly with escape
 148 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
 149 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
 150 // of previously eliminated objects occurs in realloc_objects, which is
 151 // called from the method fetch_unroll_info_helper below.
 152 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode))
 153   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
 154   // but makes the entry a little slower. There is however a little dance we have to
 155   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
 156 
 157   // fetch_unroll_info() is called at the beginning of the deoptimization
 158   // handler. Note this fact before we start generating temporary frames
 159   // that can confuse an asynchronous stack walker. This counter is
 160   // decremented at the end of unpack_frames().
 161   if (TraceDeoptimization) {
 162     tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(thread));
 163   }
 164   thread->inc_in_deopt_handler();
 165 
 166   return fetch_unroll_info_helper(thread, exec_mode);
 167 JRT_END
 168 
 169 #if COMPILER2_OR_JVMCI
 170 static bool eliminate_allocations(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,
 171                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 172                                   bool& deoptimized_objects) {
 173   bool realloc_failures = false;
 174   assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
 175 
 176   JavaThread* deoptee_thread = chunk->at(0)->thread();
 177   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread), "a frame can only be deoptimized by the owner thread");
 178 
 179   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
 180 
 181   // The flag return_oop() indicates call sites which return oop
 182   // in compiled code. Such sites include java method calls,
 183   // runtime calls (for example, used to allocate new objects/arrays
 184   // on slow code path) and any other calls generated in compiled code.
 185   // It is not guaranteed that we can get such information here only
 186   // by analyzing bytecode in deoptimized frames. This is why this flag
 187   // is set during method compilation (see Compile::Process_OopMap_Node()).
 188   // If the previous frame was popped or if we are dispatching an exception,
 189   // we don't have an oop result.
 190   bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 191   Handle return_value;
 192   if (save_oop_result) {
 193     // Reallocation may trigger GC. If deoptimization happened on return from
 194     // call which returns oop we need to save it since it is not in oopmap.
 195     oop result = deoptee.saved_oop_result(&map);
 196     assert(oopDesc::is_oop_or_null(result), "must be oop");
 197     return_value = Handle(thread, result);
 198     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 199     if (TraceDeoptimization) {
 200       ttyLocker ttyl;
 201       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 202     }
 203   }
 204   if (objects != NULL) {
 205     if (exec_mode == Deoptimization::Unpack_none) {
 206       assert(thread->thread_state() == _thread_in_vm, "assumption");
 207       Thread* THREAD = thread;
 208       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 209       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
 210       deoptimized_objects = true;
 211     } else {
 212       JRT_BLOCK
 213       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
 214       JRT_END
 215     }
 216     bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci();
 217     Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
 218 #ifndef PRODUCT
 219     if (TraceDeoptimization) {
 220       ttyLocker ttyl;
 221       tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 222       Deoptimization::print_objects(objects, realloc_failures);
 223     }
 224 #endif
 225   }
 226   if (save_oop_result) {
 227     // Restore result.
 228     deoptee.set_saved_oop_result(&map, return_value());
 229   }
 230   return realloc_failures;
 231 }
 232 
 233 static void eliminate_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 234                             frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 235   JavaThread* deoptee_thread = chunk->at(0)->thread();
 236   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 237 
 238 #ifndef PRODUCT
 239   bool first = true;
 240 #endif
 241   for (int i = 0; i < chunk->length(); i++) {
 242     compiledVFrame* cvf = chunk->at(i);
 243     assert (cvf->scope() != NULL,"expect only compiled java frames");
 244     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 245     if (monitors->is_nonempty()) {
 246       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee, exec_mode, realloc_failures);
 247       deoptimized_objects = deoptimized_objects || relocked;
 248 #ifndef PRODUCT
 249       if (PrintDeoptimizationDetails) {
 250         ttyLocker ttyl;
 251         for (int j = 0; j < monitors->length(); j++) {
 252           MonitorInfo* mi = monitors->at(j);
 253           if (mi->eliminated()) {
 254             if (first) {
 255               first = false;
 256               tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 257             }
 258             if (exec_mode == Deoptimization::Unpack_none) {
 259               ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
 260               if (monitor != NULL && (oop)monitor->object() == mi->owner()) {
 261                 tty->print_cr("     object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
 262                 continue;
 263               }
 264             }
 265             if (mi->owner_is_scalar_replaced()) {
 266               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 267               tty->print_cr("     failed reallocation for klass %s", k->external_name());
 268             } else {
 269               tty->print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 270             }
 271           }
 272         }
 273       }
 274 #endif // !PRODUCT
 275     }
 276   }
 277 }
 278 
 279 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
 280 // The given vframes cover one physical frame.
 281 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool& realloc_failures) {
 282   frame deoptee = chunk->at(0)->fr();
 283   JavaThread* deoptee_thread = chunk->at(0)->thread();
 284   CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
 285   RegisterMap map(chunk->at(0)->register_map());
 286   bool deoptimized_objects = false;
 287 
 288   // Reallocate the non-escaping objects and restore their fields. Then
 289   // relock objects if synchronization on them was eliminated.
 290   if (DoEscapeAnalysis && EliminateAllocations) {
 291     realloc_failures = eliminate_allocations(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects);
 292   }
 293 
 294   // Revoke biases of objects with eliminated locks in the given frame.
 295   Deoptimization::revoke_for_object_deoptimization(deoptee_thread, deoptee, &map, thread);
 296 
 297   // MonitorInfo structures used in eliminate_locks are not GC safe.
 298   NoSafepointVerifier no_safepoint;
 299 
 300   if ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) {
 301     eliminate_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
 302   }
 303   return deoptimized_objects;
 304 }
 305 #endif // COMPILER2_OR_JVMCI
 306 
 307 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 308 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) {
 309 
 310   // Note: there is a safepoint safety issue here. No matter whether we enter
 311   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
 312   // the vframeArray is created.
 313   //
 314 
 315   // Allocate our special deoptimization ResourceMark
 316   DeoptResourceMark* dmark = new DeoptResourceMark(thread);
 317   assert(thread->deopt_mark() == NULL, "Pending deopt!");
 318   thread->set_deopt_mark(dmark);
 319 
 320   frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
 321   RegisterMap map(thread, true);
 322   RegisterMap dummy_map(thread, false);
 323   // Now get the deoptee with a valid map
 324   frame deoptee = stub_frame.sender(&map);
 325   // Set the deoptee nmethod
 326   assert(thread->deopt_compiled_method() == NULL, "Pending deopt!");
 327   CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
 328   thread->set_deopt_compiled_method(cm);
 329 
 330   if (VerifyStack) {
 331     thread->validate_frame_layout();
 332   }
 333 
 334   // Create a growable array of VFrames where each VFrame represents an inlined
 335   // Java frame.  This storage is allocated with the usual system arena.
 336   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 337   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 338   vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
 339   while (!vf->is_top()) {
 340     assert(vf->is_compiled_frame(), "Wrong frame type");
 341     chunk->push(compiledVFrame::cast(vf));
 342     vf = vf->sender();
 343   }
 344   assert(vf->is_compiled_frame(), "Wrong frame type");
 345   chunk->push(compiledVFrame::cast(vf));
 346 
 347   bool realloc_failures = false;
 348 
 349 #if COMPILER2_OR_JVMCI
 350 #if INCLUDE_JVMCI
 351   bool jvmci_enabled = true;
 352 #else
 353   bool jvmci_enabled = false;
 354 #endif
 355 
 356   // Reallocate the non-escaping objects and restore their fields. Then
 357   // relock objects if synchronization on them was eliminated.
 358   if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations) )) {
 359     bool unused;
 360     realloc_failures = eliminate_allocations(thread, exec_mode, cm, deoptee, map, chunk, unused);
 361   }
 362 #endif // COMPILER2_OR_JVMCI
 363 
 364   // Revoke biases, done with in java state.
 365   // No safepoints allowed after this
 366   revoke_from_deopt_handler(thread, deoptee, &map);
 367 
 368   // Ensure that no safepoint is taken after pointers have been stored
 369   // in fields of rematerialized objects.  If a safepoint occurs from here on
 370   // out the java state residing in the vframeArray will be missed.
 371   // Locks may be rebaised in a safepoint.
 372   NoSafepointVerifier no_safepoint;
 373 
 374 #if COMPILER2_OR_JVMCI
 375   if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))
 376       && !EscapeBarrier::objs_are_deoptimized(thread, deoptee.id())) {
 377     bool unused;
 378     eliminate_locks(thread, chunk, realloc_failures, deoptee, exec_mode, unused);
 379   }
 380 #endif // COMPILER2_OR_JVMCI
 381 
 382   ScopeDesc* trap_scope = chunk->at(0)->scope();
 383   Handle exceptionObject;
 384   if (trap_scope->rethrow_exception()) {
 385     if (PrintDeoptimizationDetails) {
 386       tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
 387     }
 388     GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
 389     guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");
 390     ScopeValue* topOfStack = expressions->top();
 391     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 392     guarantee(exceptionObject() != NULL, "exception oop can not be null");
 393   }
 394 
 395   vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
 396 #if COMPILER2_OR_JVMCI
 397   if (realloc_failures) {
 398     pop_frames_failed_reallocs(thread, array);
 399   }
 400 #endif
 401 
 402   assert(thread->vframe_array_head() == NULL, "Pending deopt!");
 403   thread->set_vframe_array_head(array);
 404 
 405   // Now that the vframeArray has been created if we have any deferred local writes
 406   // added by jvmti then we can free up that structure as the data is now in the
 407   // vframeArray
 408 
 409   if (JvmtiDeferredUpdates::deferred_locals(thread) != NULL) {
 410     GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread);
 411     int i = 0;
 412     do {
 413       // Because of inlining we could have multiple vframes for a single frame
 414       // and several of the vframes could have deferred writes. Find them all.
 415       if (list->at(i)->id() == array->original().id()) {
 416         jvmtiDeferredLocalVariableSet* dlv = list->at(i);
 417         list->remove_at(i);
 418         // individual jvmtiDeferredLocalVariableSet are CHeapObj's
 419         delete dlv;
 420       } else {
 421         i++;
 422       }
 423     } while ( i < list->length() );
 424     if (list->length() == 0) {
 425       JvmtiDeferredUpdates* updates = thread->deferred_updates();
 426       thread->set_deferred_updates(NULL);
 427       // free deferred updates.
 428       delete updates;
 429     }
 430 
 431   }
 432 
 433   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 434   CodeBlob* cb = stub_frame.cb();
 435   // Verify we have the right vframeArray
 436   assert(cb->frame_size() >= 0, "Unexpected frame size");
 437   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 438 
 439   // If the deopt call site is a MethodHandle invoke call site we have
 440   // to adjust the unpack_sp.
 441   nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
 442   if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
 443     unpack_sp = deoptee.unextended_sp();
 444 
 445 #ifdef ASSERT
 446   assert(cb->is_deoptimization_stub() ||
 447          cb->is_uncommon_trap_stub() ||
 448          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 449          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 450          "unexpected code blob: %s", cb->name());
 451 #endif
 452 
 453   // This is a guarantee instead of an assert because if vframe doesn't match
 454   // we will unpack the wrong deoptimized frame and wind up in strange places
 455   // where it will be very difficult to figure out what went wrong. Better
 456   // to die an early death here than some very obscure death later when the
 457   // trail is cold.
 458   // Note: on ia64 this guarantee can be fooled by frames with no memory stack
 459   // in that it will fail to detect a problem when there is one. This needs
 460   // more work in tiger timeframe.
 461   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 462 
 463   int number_of_frames = array->frames();
 464 
 465   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 466   // virtual activation, which is the reverse of the elements in the vframes array.
 467   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 468   // +1 because we always have an interpreter return address for the final slot.
 469   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 470   int popframe_extra_args = 0;
 471   // Create an interpreter return address for the stub to use as its return
 472   // address so the skeletal frames are perfectly walkable
 473   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 474 
 475   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 476   // activation be put back on the expression stack of the caller for reexecution
 477   if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
 478     popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
 479   }
 480 
 481   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 482   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 483   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 484   //
 485   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 486   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 487 
 488   // It's possible that the number of parameters at the call site is
 489   // different than number of arguments in the callee when method
 490   // handles are used.  If the caller is interpreted get the real
 491   // value so that the proper amount of space can be added to it's
 492   // frame.
 493   bool caller_was_method_handle = false;
 494   if (deopt_sender.is_interpreted_frame()) {
 495     methodHandle method(thread, deopt_sender.interpreter_frame_method());
 496     Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
 497     if (cur.is_invokedynamic() || cur.is_invokehandle()) {
 498       // Method handle invokes may involve fairly arbitrary chains of
 499       // calls so it's impossible to know how much actual space the
 500       // caller has for locals.
 501       caller_was_method_handle = true;
 502     }
 503   }
 504 
 505   //
 506   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 507   // frame_sizes/frame_pcs[1] next oldest frame (int)
 508   // frame_sizes/frame_pcs[n] youngest frame (int)
 509   //
 510   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 511   // owns the space for the return address to it's caller).  Confusing ain't it.
 512   //
 513   // The vframe array can address vframes with indices running from
 514   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 515   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 516   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 517   // so things look a little strange in this loop.
 518   //
 519   int callee_parameters = 0;
 520   int callee_locals = 0;
 521   for (int index = 0; index < array->frames(); index++ ) {
 522     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 523     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 524     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 525     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 526                                                                                                     callee_locals,
 527                                                                                                     index == 0,
 528                                                                                                     popframe_extra_args);
 529     // This pc doesn't have to be perfect just good enough to identify the frame
 530     // as interpreted so the skeleton frame will be walkable
 531     // The correct pc will be set when the skeleton frame is completely filled out
 532     // The final pc we store in the loop is wrong and will be overwritten below
 533     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 534 
 535     callee_parameters = array->element(index)->method()->size_of_parameters();
 536     callee_locals = array->element(index)->method()->max_locals();
 537     popframe_extra_args = 0;
 538   }
 539 
 540   // Compute whether the root vframe returns a float or double value.
 541   BasicType return_type;
 542   {
 543     methodHandle method(thread, array->element(0)->method());
 544     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 545     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 546   }
 547 
 548   // Compute information for handling adapters and adjusting the frame size of the caller.
 549   int caller_adjustment = 0;
 550 
 551   // Compute the amount the oldest interpreter frame will have to adjust
 552   // its caller's stack by. If the caller is a compiled frame then
 553   // we pretend that the callee has no parameters so that the
 554   // extension counts for the full amount of locals and not just
 555   // locals-parms. This is because without a c2i adapter the parm
 556   // area as created by the compiled frame will not be usable by
 557   // the interpreter. (Depending on the calling convention there
 558   // may not even be enough space).
 559 
 560   // QQQ I'd rather see this pushed down into last_frame_adjust
 561   // and have it take the sender (aka caller).
 562 
 563   if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
 564     caller_adjustment = last_frame_adjust(0, callee_locals);
 565   } else if (callee_locals > callee_parameters) {
 566     // The caller frame may need extending to accommodate
 567     // non-parameter locals of the first unpacked interpreted frame.
 568     // Compute that adjustment.
 569     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 570   }
 571 
 572   // If the sender is deoptimized the we must retrieve the address of the handler
 573   // since the frame will "magically" show the original pc before the deopt
 574   // and we'd undo the deopt.
 575 
 576   frame_pcs[0] = deopt_sender.raw_pc();
 577 
 578   assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
 579 
 580 #if INCLUDE_JVMCI
 581   if (exceptionObject() != NULL) {
 582     thread->set_exception_oop(exceptionObject());
 583     exec_mode = Unpack_exception;
 584   }
 585 #endif
 586 
 587   if (thread->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 588     assert(thread->has_pending_exception(), "should have thrown OOME");
 589     thread->set_exception_oop(thread->pending_exception());
 590     thread->clear_pending_exception();
 591     exec_mode = Unpack_exception;
 592   }
 593 
 594 #if INCLUDE_JVMCI
 595   if (thread->frames_to_pop_failed_realloc() > 0) {
 596     thread->set_pending_monitorenter(false);
 597   }
 598 #endif
 599 
 600   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 601                                       caller_adjustment * BytesPerWord,
 602                                       caller_was_method_handle ? 0 : callee_parameters,
 603                                       number_of_frames,
 604                                       frame_sizes,
 605                                       frame_pcs,
 606                                       return_type,
 607                                       exec_mode);
 608   // On some platforms, we need a way to pass some platform dependent
 609   // information to the unpacking code so the skeletal frames come out
 610   // correct (initial fp value, unextended sp, ...)
 611   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 612 
 613   if (array->frames() > 1) {
 614     if (VerifyStack && TraceDeoptimization) {
 615       ttyLocker ttyl;
 616       tty->print_cr("Deoptimizing method containing inlining");
 617     }
 618   }
 619 
 620   array->set_unroll_block(info);
 621   return info;
 622 }
 623 
 624 // Called to cleanup deoptimization data structures in normal case
 625 // after unpacking to stack and when stack overflow error occurs
 626 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 627                                         vframeArray *array) {
 628 
 629   // Get array if coming from exception
 630   if (array == NULL) {
 631     array = thread->vframe_array_head();
 632   }
 633   thread->set_vframe_array_head(NULL);
 634 
 635   // Free the previous UnrollBlock
 636   vframeArray* old_array = thread->vframe_array_last();
 637   thread->set_vframe_array_last(array);
 638 
 639   if (old_array != NULL) {
 640     UnrollBlock* old_info = old_array->unroll_block();
 641     old_array->set_unroll_block(NULL);
 642     delete old_info;
 643     delete old_array;
 644   }
 645 
 646   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 647   // inside the vframeArray (StackValueCollections)
 648 
 649   delete thread->deopt_mark();
 650   thread->set_deopt_mark(NULL);
 651   thread->set_deopt_compiled_method(NULL);
 652 
 653 
 654   if (JvmtiExport::can_pop_frame()) {
 655     // Regardless of whether we entered this routine with the pending
 656     // popframe condition bit set, we should always clear it now
 657     thread->clear_popframe_condition();
 658   }
 659 
 660   // unpack_frames() is called at the end of the deoptimization handler
 661   // and (in C2) at the end of the uncommon trap handler. Note this fact
 662   // so that an asynchronous stack walker can work again. This counter is
 663   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 664   // the beginning of uncommon_trap().
 665   thread->dec_in_deopt_handler();
 666 }
 667 
 668 // Moved from cpu directories because none of the cpus has callee save values.
 669 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 670 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 671 
 672   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 673   // the days we had adapter frames. When we deoptimize a situation where a
 674   // compiled caller calls a compiled caller will have registers it expects
 675   // to survive the call to the callee. If we deoptimize the callee the only
 676   // way we can restore these registers is to have the oldest interpreter
 677   // frame that we create restore these values. That is what this routine
 678   // will accomplish.
 679 
 680   // At the moment we have modified c2 to not have any callee save registers
 681   // so this problem does not exist and this routine is just a place holder.
 682 
 683   assert(f->is_interpreted_frame(), "must be interpreted");
 684 }
 685 
 686 // Return BasicType of value being returned
 687 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 688 
 689   // We are already active in the special DeoptResourceMark any ResourceObj's we
 690   // allocate will be freed at the end of the routine.
 691 
 692   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
 693   // but makes the entry a little slower. There is however a little dance we have to
 694   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
 695   ResetNoHandleMark rnhm; // No-op in release/product versions
 696   HandleMark hm;
 697 
 698   frame stub_frame = thread->last_frame();
 699 
 700   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 701   // must point to the vframeArray for the unpack frame.
 702   vframeArray* array = thread->vframe_array_head();
 703 
 704 #ifndef PRODUCT
 705   if (TraceDeoptimization) {
 706     ttyLocker ttyl;
 707     tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",
 708                   p2i(thread), p2i(array), exec_mode);
 709   }
 710 #endif
 711   Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
 712               p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);
 713 
 714   UnrollBlock* info = array->unroll_block();
 715 
 716   // We set the last_Java frame. But the stack isn't really parsable here. So we
 717   // clear it to make sure JFR understands not to try and walk stacks from events
 718   // in here.
 719   intptr_t* sp = thread->frame_anchor()->last_Java_sp();
 720   thread->frame_anchor()->set_last_Java_sp(NULL);
 721 
 722   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 723   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 724 
 725   thread->frame_anchor()->set_last_Java_sp(sp);
 726 
 727   BasicType bt = info->return_type();
 728 
 729   // If we have an exception pending, claim that the return type is an oop
 730   // so the deopt_blob does not overwrite the exception_oop.
 731 
 732   if (exec_mode == Unpack_exception)
 733     bt = T_OBJECT;
 734 
 735   // Cleanup thread deopt data
 736   cleanup_deopt_info(thread, array);
 737 
 738 #ifndef PRODUCT
 739   if (VerifyStack) {
 740     ResourceMark res_mark;
 741     // Clear pending exception to not break verification code (restored afterwards)
 742     PRESERVE_EXCEPTION_MARK;
 743 
 744     thread->validate_frame_layout();
 745 
 746     // Verify that the just-unpacked frames match the interpreter's
 747     // notions of expression stack and locals
 748     vframeArray* cur_array = thread->vframe_array_last();
 749     RegisterMap rm(thread, false);
 750     rm.set_include_argument_oops(false);
 751     bool is_top_frame = true;
 752     int callee_size_of_parameters = 0;
 753     int callee_max_locals = 0;
 754     for (int i = 0; i < cur_array->frames(); i++) {
 755       vframeArrayElement* el = cur_array->element(i);
 756       frame* iframe = el->iframe();
 757       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 758 
 759       // Get the oop map for this bci
 760       InterpreterOopMap mask;
 761       int cur_invoke_parameter_size = 0;
 762       bool try_next_mask = false;
 763       int next_mask_expression_stack_size = -1;
 764       int top_frame_expression_stack_adjustment = 0;
 765       methodHandle mh(thread, iframe->interpreter_frame_method());
 766       OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
 767       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 768       int max_bci = mh->code_size();
 769       // Get to the next bytecode if possible
 770       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 771       // Check to see if we can grab the number of outgoing arguments
 772       // at an uncommon trap for an invoke (where the compiler
 773       // generates debug info before the invoke has executed)
 774       Bytecodes::Code cur_code = str.next();
 775       if (Bytecodes::is_invoke(cur_code)) {
 776         Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
 777         cur_invoke_parameter_size = invoke.size_of_parameters();
 778         if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
 779           callee_size_of_parameters++;
 780         }
 781       }
 782       if (str.bci() < max_bci) {
 783         Bytecodes::Code next_code = str.next();
 784         if (next_code >= 0) {
 785           // The interpreter oop map generator reports results before
 786           // the current bytecode has executed except in the case of
 787           // calls. It seems to be hard to tell whether the compiler
 788           // has emitted debug information matching the "state before"
 789           // a given bytecode or the state after, so we try both
 790           if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) {
 791             // Get expression stack size for the next bytecode
 792             InterpreterOopMap next_mask;
 793             OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
 794             next_mask_expression_stack_size = next_mask.expression_stack_size();
 795             if (Bytecodes::is_invoke(next_code)) {
 796               Bytecode_invoke invoke(mh, str.bci());
 797               next_mask_expression_stack_size += invoke.size_of_parameters();
 798             }
 799             // Need to subtract off the size of the result type of
 800             // the bytecode because this is not described in the
 801             // debug info but returned to the interpreter in the TOS
 802             // caching register
 803             BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
 804             if (bytecode_result_type != T_ILLEGAL) {
 805               top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
 806             }
 807             assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
 808             try_next_mask = true;
 809           }
 810         }
 811       }
 812 
 813       // Verify stack depth and oops in frame
 814       // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
 815       if (!(
 816             /* SPARC */
 817             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
 818             /* x86 */
 819             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
 820             (try_next_mask &&
 821              (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
 822                                                                     top_frame_expression_stack_adjustment))) ||
 823             (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
 824             (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
 825              (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
 826             )) {
 827         {
 828           ttyLocker ttyl;
 829 
 830           // Print out some information that will help us debug the problem
 831           tty->print_cr("Wrong number of expression stack elements during deoptimization");
 832           tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
 833           tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
 834                         iframe->interpreter_frame_expression_stack_size());
 835           tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
 836           tty->print_cr("  try_next_mask = %d", try_next_mask);
 837           tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
 838           tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
 839           tty->print_cr("  callee_max_locals = %d", callee_max_locals);
 840           tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
 841           tty->print_cr("  exec_mode = %d", exec_mode);
 842           tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
 843           tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
 844           tty->print_cr("  Interpreted frames:");
 845           for (int k = 0; k < cur_array->frames(); k++) {
 846             vframeArrayElement* el = cur_array->element(k);
 847             tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
 848           }
 849           cur_array->print_on_2(tty);
 850         } // release tty lock before calling guarantee
 851         guarantee(false, "wrong number of expression stack elements during deopt");
 852       }
 853       VerifyOopClosure verify;
 854       iframe->oops_interpreted_do(&verify, &rm, false);
 855       callee_size_of_parameters = mh->size_of_parameters();
 856       callee_max_locals = mh->max_locals();
 857       is_top_frame = false;
 858     }
 859   }
 860 #endif /* !PRODUCT */
 861 
 862   return bt;
 863 JRT_END
 864 
 865 class DeoptimizeMarkedClosure : public HandshakeClosure {
 866  public:
 867   DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}
 868   void do_thread(Thread* thread) {
 869     JavaThread* jt = (JavaThread*)thread;
 870     jt->deoptimize_marked_methods();
 871   }
 872 };
 873 
 874 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) {
 875   ResourceMark rm;
 876   DeoptimizationMarker dm;
 877 
 878   // Make the dependent methods not entrant
 879   if (nmethod_only != NULL) {
 880     nmethod_only->mark_for_deoptimization();
 881     nmethod_only->make_not_entrant();
 882   } else {
 883     MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag);
 884     CodeCache::make_marked_nmethods_not_entrant();
 885   }
 886 
 887   DeoptimizeMarkedClosure deopt;
 888   if (SafepointSynchronize::is_at_safepoint()) {
 889     Threads::java_threads_do(&deopt);
 890   } else {
 891     Handshake::execute(&deopt);
 892   }
 893 }
 894 
 895 Deoptimization::DeoptAction Deoptimization::_unloaded_action
 896   = Deoptimization::Action_reinterpret;
 897 
 898 
 899 
 900 #if INCLUDE_JVMCI || INCLUDE_AOT
 901 template<typename CacheType>
 902 class BoxCacheBase : public CHeapObj<mtCompiler> {
 903 protected:
 904   static InstanceKlass* find_cache_klass(Symbol* klass_name, TRAPS) {
 905     ResourceMark rm;
 906     char* klass_name_str = klass_name->as_C_string();
 907     Klass* k = SystemDictionary::find(klass_name, Handle(), Handle(), THREAD);
 908     guarantee(k != NULL, "%s must be loaded", klass_name_str);
 909     InstanceKlass* ik = InstanceKlass::cast(k);
 910     guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
 911     CacheType::compute_offsets(ik);
 912     return ik;
 913   }
 914 };
 915 
 916 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache  : public BoxCacheBase<CacheType> {
 917   PrimitiveType _low;
 918   PrimitiveType _high;
 919   jobject _cache;
 920 protected:
 921   static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
 922   BoxCache(Thread* thread) {
 923     InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol(), thread);
 924     objArrayOop cache = CacheType::cache(ik);
 925     assert(cache->length() > 0, "Empty cache");
 926     _low = BoxType::value(cache->obj_at(0));
 927     _high = _low + cache->length() - 1;
 928     _cache = JNIHandles::make_global(Handle(thread, cache));
 929   }
 930   ~BoxCache() {
 931     JNIHandles::destroy_global(_cache);
 932   }
 933 public:
 934   static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
 935     if (_singleton == NULL) {
 936       BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
 937       if (!Atomic::replace_if_null(&_singleton, s)) {
 938         delete s;
 939       }
 940     }
 941     return _singleton;
 942   }
 943   oop lookup(PrimitiveType value) {
 944     if (_low <= value && value <= _high) {
 945       int offset = value - _low;
 946       return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
 947     }
 948     return NULL;
 949   }
 950   oop lookup_raw(intptr_t raw_value) {
 951     // Have to cast to avoid little/big-endian problems.
 952     if (sizeof(PrimitiveType) > sizeof(jint)) {
 953       jlong value = (jlong)raw_value;
 954       return lookup(value);
 955     }
 956     PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
 957     return lookup(value);
 958   }
 959 };
 960 
 961 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
 962 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
 963 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
 964 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
 965 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
 966 
 967 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL;
 968 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL;
 969 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL;
 970 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL;
 971 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL;
 972 
 973 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
 974   jobject _true_cache;
 975   jobject _false_cache;
 976 protected:
 977   static BooleanBoxCache *_singleton;
 978   BooleanBoxCache(Thread *thread) {
 979     InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol(), thread);
 980     _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
 981     _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
 982   }
 983   ~BooleanBoxCache() {
 984     JNIHandles::destroy_global(_true_cache);
 985     JNIHandles::destroy_global(_false_cache);
 986   }
 987 public:
 988   static BooleanBoxCache* singleton(Thread* thread) {
 989     if (_singleton == NULL) {
 990       BooleanBoxCache* s = new BooleanBoxCache(thread);
 991       if (!Atomic::replace_if_null(&_singleton, s)) {
 992         delete s;
 993       }
 994     }
 995     return _singleton;
 996   }
 997   oop lookup_raw(intptr_t raw_value) {
 998     // Have to cast to avoid little/big-endian problems.
 999     jboolean value = (jboolean)*((jint*)&raw_value);
1000     return lookup(value);
1001   }
1002   oop lookup(jboolean value) {
1003     if (value != 0) {
1004       return JNIHandles::resolve_non_null(_true_cache);
1005     }
1006     return JNIHandles::resolve_non_null(_false_cache);
1007   }
1008 };
1009 
1010 BooleanBoxCache* BooleanBoxCache::_singleton = NULL;
1011 
1012 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) {
1013    Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
1014    BasicType box_type = SystemDictionary::box_klass_type(k);
1015    if (box_type != T_OBJECT) {
1016      StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
1017      switch(box_type) {
1018        case T_INT:     return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1019        case T_CHAR:    return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1020        case T_SHORT:   return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1021        case T_BYTE:    return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1022        case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1023        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1024        default:;
1025      }
1026    }
1027    return NULL;
1028 }
1029 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1030 
1031 #if COMPILER2_OR_JVMCI
1032 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1033   Handle pending_exception(THREAD, thread->pending_exception());
1034   const char* exception_file = thread->exception_file();
1035   int exception_line = thread->exception_line();
1036   thread->clear_pending_exception();
1037 
1038   bool failures = false;
1039 
1040   for (int i = 0; i < objects->length(); i++) {
1041     assert(objects->at(i)->is_object(), "invalid debug information");
1042     ObjectValue* sv = (ObjectValue*) objects->at(i);
1043 
1044     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1045     oop obj = NULL;
1046 
1047     if (k->is_instance_klass()) {
1048 #if INCLUDE_JVMCI || INCLUDE_AOT
1049       CompiledMethod* cm = fr->cb()->as_compiled_method_or_null();
1050       if (cm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1051         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1052         obj = get_cached_box(abv, fr, reg_map, THREAD);
1053         if (obj != NULL) {
1054           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1055           abv->set_cached(true);
1056         }
1057       }
1058 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1059       InstanceKlass* ik = InstanceKlass::cast(k);
1060       if (obj == NULL) {
1061         obj = ik->allocate_instance(THREAD);
1062       }
1063     } else if (k->is_typeArray_klass()) {
1064       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1065       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1066       int len = sv->field_size() / type2size[ak->element_type()];
1067       obj = ak->allocate(len, THREAD);
1068     } else if (k->is_objArray_klass()) {
1069       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1070       obj = ak->allocate(sv->field_size(), THREAD);
1071     }
1072 
1073     if (obj == NULL) {
1074       failures = true;
1075     }
1076 
1077     assert(sv->value().is_null(), "redundant reallocation");
1078     assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
1079     CLEAR_PENDING_EXCEPTION;
1080     sv->set_value(obj);
1081   }
1082 
1083   if (failures) {
1084     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1085   } else if (pending_exception.not_null()) {
1086     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1087   }
1088 
1089   return failures;
1090 }
1091 
1092 #if INCLUDE_JVMCI
1093 /**
1094  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1095  * we need to somehow be able to recover the actual kind to be able to write the correct
1096  * amount of bytes.
1097  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1098  * the entries at index n + 1 to n + i are 'markers'.
1099  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1100  * expected form of the array would be:
1101  *
1102  * {b0, b1, b2, b3, INT, marker, b6, b7}
1103  *
1104  * Thus, in order to get back the size of the entry, we simply need to count the number
1105  * of marked entries
1106  *
1107  * @param virtualArray the virtualized byte array
1108  * @param i index of the virtual entry we are recovering
1109  * @return The number of bytes the entry spans
1110  */
1111 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1112   int index = i;
1113   while (++index < virtualArray->field_size() &&
1114            virtualArray->field_at(index)->is_marker()) {}
1115   return index - i;
1116 }
1117 
1118 /**
1119  * If there was a guarantee for byte array to always start aligned to a long, we could
1120  * do a simple check on the parity of the index. Unfortunately, that is not always the
1121  * case. Thus, we check alignment of the actual address we are writing to.
1122  * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1123  * write a long to index 3.
1124  */
1125 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1126     jbyte* res = obj->byte_at_addr(index);
1127     assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1128     return res;
1129 }
1130 
1131 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {
1132   switch (byte_count) {
1133     case 1:
1134       obj->byte_at_put(index, (jbyte) *((jint *) &val));
1135       break;
1136     case 2:
1137       *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);
1138       break;
1139     case 4:
1140       *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);
1141       break;
1142     case 8:
1143       *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val);
1144       break;
1145     default:
1146       ShouldNotReachHere();
1147   }
1148 }
1149 #endif // INCLUDE_JVMCI
1150 
1151 
1152 // restore elements of an eliminated type array
1153 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1154   int index = 0;
1155   intptr_t val;
1156 
1157   for (int i = 0; i < sv->field_size(); i++) {
1158     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1159     switch(type) {
1160     case T_LONG: case T_DOUBLE: {
1161       assert(value->type() == T_INT, "Agreement.");
1162       StackValue* low =
1163         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1164 #ifdef _LP64
1165       jlong res = (jlong)low->get_int();
1166 #else
1167       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1168 #endif
1169       obj->long_at_put(index, res);
1170       break;
1171     }
1172 
1173     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1174     case T_INT: case T_FLOAT: { // 4 bytes.
1175       assert(value->type() == T_INT, "Agreement.");
1176       bool big_value = false;
1177       if (i + 1 < sv->field_size() && type == T_INT) {
1178         if (sv->field_at(i)->is_location()) {
1179           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1180           if (type == Location::dbl || type == Location::lng) {
1181             big_value = true;
1182           }
1183         } else if (sv->field_at(i)->is_constant_int()) {
1184           ScopeValue* next_scope_field = sv->field_at(i + 1);
1185           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1186             big_value = true;
1187           }
1188         }
1189       }
1190 
1191       if (big_value) {
1192         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1193   #ifdef _LP64
1194         jlong res = (jlong)low->get_int();
1195   #else
1196         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1197   #endif
1198         obj->int_at_put(index, (jint)*((jint*)&res));
1199         obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
1200       } else {
1201         val = value->get_int();
1202         obj->int_at_put(index, (jint)*((jint*)&val));
1203       }
1204       break;
1205     }
1206 
1207     case T_SHORT:
1208       assert(value->type() == T_INT, "Agreement.");
1209       val = value->get_int();
1210       obj->short_at_put(index, (jshort)*((jint*)&val));
1211       break;
1212 
1213     case T_CHAR:
1214       assert(value->type() == T_INT, "Agreement.");
1215       val = value->get_int();
1216       obj->char_at_put(index, (jchar)*((jint*)&val));
1217       break;
1218 
1219     case T_BYTE: {
1220       assert(value->type() == T_INT, "Agreement.");
1221       // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1222       val = value->get_int();
1223 #if INCLUDE_JVMCI
1224       int byte_count = count_number_of_bytes_for_entry(sv, i);
1225       byte_array_put(obj, val, index, byte_count);
1226       // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1227       i += byte_count - 1; // Balance the loop counter.
1228       index += byte_count;
1229       // index has been updated so continue at top of loop
1230       continue;
1231 #else
1232       obj->byte_at_put(index, (jbyte)*((jint*)&val));
1233       break;
1234 #endif // INCLUDE_JVMCI
1235     }
1236 
1237     case T_BOOLEAN: {
1238       assert(value->type() == T_INT, "Agreement.");
1239       val = value->get_int();
1240       obj->bool_at_put(index, (jboolean)*((jint*)&val));
1241       break;
1242     }
1243 
1244       default:
1245         ShouldNotReachHere();
1246     }
1247     index++;
1248   }
1249 }
1250 
1251 // restore fields of an eliminated object array
1252 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1253   for (int i = 0; i < sv->field_size(); i++) {
1254     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1255     assert(value->type() == T_OBJECT, "object element expected");
1256     obj->obj_at_put(i, value->get_obj()());
1257   }
1258 }
1259 
1260 class ReassignedField {
1261 public:
1262   int _offset;
1263   BasicType _type;
1264 public:
1265   ReassignedField() {
1266     _offset = 0;
1267     _type = T_ILLEGAL;
1268   }
1269 };
1270 
1271 int compare(ReassignedField* left, ReassignedField* right) {
1272   return left->_offset - right->_offset;
1273 }
1274 
1275 // Restore fields of an eliminated instance object using the same field order
1276 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
1277 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
1278   GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
1279   InstanceKlass* ik = klass;
1280   while (ik != NULL) {
1281     for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1282       if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
1283         ReassignedField field;
1284         field._offset = fs.offset();
1285         field._type = Signature::basic_type(fs.signature());
1286         fields->append(field);
1287       }
1288     }
1289     ik = ik->superklass();
1290   }
1291   fields->sort(compare);
1292   for (int i = 0; i < fields->length(); i++) {
1293     intptr_t val;
1294     ScopeValue* scope_field = sv->field_at(svIndex);
1295     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1296     int offset = fields->at(i)._offset;
1297     BasicType type = fields->at(i)._type;
1298     switch (type) {
1299       case T_OBJECT: case T_ARRAY:
1300         assert(value->type() == T_OBJECT, "Agreement.");
1301         obj->obj_field_put(offset, value->get_obj()());
1302         break;
1303 
1304       // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1305       case T_INT: case T_FLOAT: { // 4 bytes.
1306         assert(value->type() == T_INT, "Agreement.");
1307         bool big_value = false;
1308         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1309           if (scope_field->is_location()) {
1310             Location::Type type = ((LocationValue*) scope_field)->location().type();
1311             if (type == Location::dbl || type == Location::lng) {
1312               big_value = true;
1313             }
1314           }
1315           if (scope_field->is_constant_int()) {
1316             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1317             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1318               big_value = true;
1319             }
1320           }
1321         }
1322 
1323         if (big_value) {
1324           i++;
1325           assert(i < fields->length(), "second T_INT field needed");
1326           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1327         } else {
1328           val = value->get_int();
1329           obj->int_field_put(offset, (jint)*((jint*)&val));
1330           break;
1331         }
1332       }
1333         /* no break */
1334 
1335       case T_LONG: case T_DOUBLE: {
1336         assert(value->type() == T_INT, "Agreement.");
1337         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1338 #ifdef _LP64
1339         jlong res = (jlong)low->get_int();
1340 #else
1341         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1342 #endif
1343         obj->long_field_put(offset, res);
1344         break;
1345       }
1346 
1347       case T_SHORT:
1348         assert(value->type() == T_INT, "Agreement.");
1349         val = value->get_int();
1350         obj->short_field_put(offset, (jshort)*((jint*)&val));
1351         break;
1352 
1353       case T_CHAR:
1354         assert(value->type() == T_INT, "Agreement.");
1355         val = value->get_int();
1356         obj->char_field_put(offset, (jchar)*((jint*)&val));
1357         break;
1358 
1359       case T_BYTE:
1360         assert(value->type() == T_INT, "Agreement.");
1361         val = value->get_int();
1362         obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1363         break;
1364 
1365       case T_BOOLEAN:
1366         assert(value->type() == T_INT, "Agreement.");
1367         val = value->get_int();
1368         obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1369         break;
1370 
1371       default:
1372         ShouldNotReachHere();
1373     }
1374     svIndex++;
1375   }
1376   return svIndex;
1377 }
1378 
1379 // restore fields of all eliminated objects and arrays
1380 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
1381   for (int i = 0; i < objects->length(); i++) {
1382     ObjectValue* sv = (ObjectValue*) objects->at(i);
1383     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1384     Handle obj = sv->value();
1385     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1386     if (PrintDeoptimizationDetails) {
1387       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1388     }
1389     if (obj.is_null()) {
1390       continue;
1391     }
1392 #if INCLUDE_JVMCI || INCLUDE_AOT
1393     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1394     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1395       continue;
1396     }
1397 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1398     if (k->is_instance_klass()) {
1399       InstanceKlass* ik = InstanceKlass::cast(k);
1400       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);
1401     } else if (k->is_typeArray_klass()) {
1402       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1403       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1404     } else if (k->is_objArray_klass()) {
1405       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1406     }
1407   }
1408 }
1409 
1410 
1411 // relock objects for which synchronization was eliminated
1412 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1413                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1414   bool relocked_objects = false;
1415   for (int i = 0; i < monitors->length(); i++) {
1416     MonitorInfo* mon_info = monitors->at(i);
1417     if (mon_info->eliminated()) {
1418       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1419       relocked_objects = true;
1420       if (!mon_info->owner_is_scalar_replaced()) {
1421         Handle obj(thread, mon_info->owner());
1422         markWord mark = obj->mark();
1423         if (UseBiasedLocking && mark.has_bias_pattern()) {
1424           // New allocated objects may have the mark set to anonymously biased.
1425           // Also the deoptimized method may called methods with synchronization
1426           // where the thread-local object is bias locked to the current thread.
1427           assert(mark.is_biased_anonymously() ||
1428                  mark.biased_locker() == deoptee_thread, "should be locked to current thread");
1429           // Reset mark word to unbiased prototype.
1430           markWord unbiased_prototype = markWord::prototype().set_age(mark.age());
1431           obj->set_mark(unbiased_prototype);
1432         } else if (exec_mode == Unpack_none) {
1433           if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {
1434             // With exec_mode == Unpack_none obj may be thread local and locked in
1435             // a callee frame. In this case the bias was revoked before in revoke_for_object_deoptimization().
1436             // Make the lock in the callee a recursive lock and restore the displaced header.
1437             markWord dmw = mark.displaced_mark_helper();
1438             mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL));
1439             obj->set_mark(dmw);
1440           }
1441           if (mark.has_monitor()) {
1442             // defer relocking if the deoptee thread is currently waiting for obj
1443             ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1444             if (waiting_monitor != NULL && (oop)waiting_monitor->object() == obj()) {
1445               assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1446               mon_info->lock()->set_displaced_header(markWord::unused_mark());
1447               JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1448               continue;
1449             }
1450           }
1451         }
1452         BasicLock* lock = mon_info->lock();
1453         ObjectSynchronizer::enter(obj, lock, deoptee_thread);
1454         assert(mon_info->owner()->is_locked(), "object must be locked now");
1455       }
1456     }
1457   }
1458   return relocked_objects;
1459 }
1460 
1461 
1462 #ifndef PRODUCT
1463 // print information about reallocated objects
1464 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
1465   fieldDescriptor fd;
1466 
1467   for (int i = 0; i < objects->length(); i++) {
1468     ObjectValue* sv = (ObjectValue*) objects->at(i);
1469     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1470     Handle obj = sv->value();
1471 
1472     tty->print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
1473     k->print_value();
1474     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1475     if (obj.is_null()) {
1476       tty->print(" allocation failed");
1477     } else {
1478       tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
1479     }
1480     tty->cr();
1481 
1482     if (Verbose && !obj.is_null()) {
1483       k->oop_print_on(obj(), tty);
1484     }
1485   }
1486 }
1487 #endif
1488 #endif // COMPILER2_OR_JVMCI
1489 
1490 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1491   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1492 
1493 #ifndef PRODUCT
1494   if (PrintDeoptimizationDetails) {
1495     ttyLocker ttyl;
1496     tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));
1497     fr.print_on(tty);
1498     tty->print_cr("     Virtual frames (innermost first):");
1499     for (int index = 0; index < chunk->length(); index++) {
1500       compiledVFrame* vf = chunk->at(index);
1501       tty->print("       %2d - ", index);
1502       vf->print_value();
1503       int bci = chunk->at(index)->raw_bci();
1504       const char* code_name;
1505       if (bci == SynchronizationEntryBCI) {
1506         code_name = "sync entry";
1507       } else {
1508         Bytecodes::Code code = vf->method()->code_at(bci);
1509         code_name = Bytecodes::name(code);
1510       }
1511       tty->print(" - %s", code_name);
1512       tty->print_cr(" @ bci %d ", bci);
1513       if (Verbose) {
1514         vf->print();
1515         tty->cr();
1516       }
1517     }
1518   }
1519 #endif
1520 
1521   // Register map for next frame (used for stack crawl).  We capture
1522   // the state of the deopt'ing frame's caller.  Thus if we need to
1523   // stuff a C2I adapter we can properly fill in the callee-save
1524   // register locations.
1525   frame caller = fr.sender(reg_map);
1526   int frame_size = caller.sp() - fr.sp();
1527 
1528   frame sender = caller;
1529 
1530   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1531   // the vframeArray containing the unpacking information is allocated in the C heap.
1532   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1533   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1534 
1535   // Compare the vframeArray to the collected vframes
1536   assert(array->structural_compare(thread, chunk), "just checking");
1537 
1538 #ifndef PRODUCT
1539   if (PrintDeoptimizationDetails) {
1540     ttyLocker ttyl;
1541     tty->print_cr("     Created vframeArray " INTPTR_FORMAT, p2i(array));
1542   }
1543 #endif // PRODUCT
1544 
1545   return array;
1546 }
1547 
1548 #if COMPILER2_OR_JVMCI
1549 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1550   // Reallocation of some scalar replaced objects failed. Record
1551   // that we need to pop all the interpreter frames for the
1552   // deoptimized compiled frame.
1553   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1554   thread->set_frames_to_pop_failed_realloc(array->frames());
1555   // Unlock all monitors here otherwise the interpreter will see a
1556   // mix of locked and unlocked monitors (because of failed
1557   // reallocations of synchronized objects) and be confused.
1558   for (int i = 0; i < array->frames(); i++) {
1559     MonitorChunk* monitors = array->element(i)->monitors();
1560     if (monitors != NULL) {
1561       for (int j = 0; j < monitors->number_of_monitors(); j++) {
1562         BasicObjectLock* src = monitors->at(j);
1563         if (src->obj() != NULL) {
1564           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1565         }
1566       }
1567       array->element(i)->free_monitors(thread);
1568 #ifdef ASSERT
1569       array->element(i)->set_removed_monitors();
1570 #endif
1571     }
1572   }
1573 }
1574 #endif
1575 
1576 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke, bool only_eliminated) {
1577   GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1578   Thread* thread = Thread::current();
1579   for (int i = 0; i < monitors->length(); i++) {
1580     MonitorInfo* mon_info = monitors->at(i);
1581     if ((mon_info->eliminated() == only_eliminated) && !mon_info->owner_is_scalar_replaced() && mon_info->owner() != NULL) {
1582       objects_to_revoke->append(Handle(thread, mon_info->owner()));
1583     }
1584   }
1585 }
1586 
1587 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, frame fr, RegisterMap* map,
1588                                     bool only_eliminated) {
1589   // Unfortunately we don't have a RegisterMap available in most of
1590   // the places we want to call this routine so we need to walk the
1591   // stack again to update the register map.
1592   if (map == NULL || !map->update_map()) {
1593     StackFrameStream sfs(thread, true);
1594     bool found = false;
1595     while (!found && !sfs.is_done()) {
1596       frame* cur = sfs.current();
1597       sfs.next();
1598       found = cur->id() == fr.id();
1599     }
1600     assert(found, "frame to be deoptimized not found on target thread's stack");
1601     map = sfs.register_map();
1602   }
1603 
1604   vframe* vf = vframe::new_vframe(&fr, map, thread);
1605   compiledVFrame* cvf = compiledVFrame::cast(vf);
1606   // Revoke monitors' biases in all scopes
1607   while (!cvf->is_top()) {
1608     collect_monitors(cvf, objects_to_revoke, only_eliminated);
1609     cvf = compiledVFrame::cast(cvf->sender());
1610   }
1611   collect_monitors(cvf, objects_to_revoke, only_eliminated);
1612 }
1613 
1614 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) {
1615   if (!UseBiasedLocking) {
1616     return;
1617   }
1618   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1619   get_monitors_from_stack(objects_to_revoke, thread, fr, map, false);
1620 
1621   int len = objects_to_revoke->length();
1622   for (int i = 0; i < len; i++) {
1623     oop obj = (objects_to_revoke->at(i))();
1624     BiasedLocking::revoke_own_lock(objects_to_revoke->at(i), thread);
1625     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
1626   }
1627 }
1628 
1629 // Revoke the bias of objects with eliminated locking to prepare subsequent relocking.
1630 void Deoptimization::revoke_for_object_deoptimization(JavaThread* deoptee_thread, frame fr, RegisterMap* map, JavaThread* thread) {
1631   if (!UseBiasedLocking) {
1632     return;
1633   }
1634   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1635   // Collect monitors, but only those with eliminated locking.
1636   get_monitors_from_stack(objects_to_revoke, deoptee_thread, fr, map, true);
1637 
1638   int len = objects_to_revoke->length();
1639   for (int i = 0; i < len; i++) {
1640     oop obj = (objects_to_revoke->at(i))();
1641     markWord mark = obj->mark();
1642     if (!mark.has_bias_pattern()
1643         || mark.is_biased_anonymously() // eliminated locking does not bias an object if it wasn't before
1644         || !obj->klass()->prototype_header().has_bias_pattern() // bulk revoke ignores eliminated monitors
1645         || (obj->klass()->prototype_header().bias_epoch() != mark.bias_epoch())) { // bulk rebias ignores eliminated monitors
1646       // We reach here regularly if there's just eliminated locking on obj.
1647       // We must not call BiasedLocking::revoke_own_lock() in this case, as we would hit assertions, because it is a
1648       // prerequisite that there has to be non-eliminated locking on obj by deoptee_thread.
1649       // Luckily we don't have to revoke here, because obj has to be a  non-escaping obj and can be relocked without
1650       // revoking the bias. See Deoptimization::relock_objects().
1651       continue;
1652     }
1653     BiasedLocking::revoke(objects_to_revoke->at(i), thread);
1654     assert(!objects_to_revoke->at(i)->mark().has_bias_pattern(), "biases should be revoked by now");
1655   }
1656 }
1657 
1658 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1659   assert(fr.can_be_deoptimized(), "checking frame type");
1660 
1661   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1662 
1663   if (LogCompilation && xtty != NULL) {
1664     CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();
1665     assert(cm != NULL, "only compiled methods can deopt");
1666 
1667     ttyLocker ttyl;
1668     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1669     cm->log_identity(xtty);
1670     xtty->end_head();
1671     for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1672       xtty->begin_elem("jvms bci='%d'", sd->bci());
1673       xtty->method(sd->method());
1674       xtty->end_elem();
1675       if (sd->is_top())  break;
1676     }
1677     xtty->tail("deoptimized");
1678   }
1679 
1680   // Patch the compiled method so that when execution returns to it we will
1681   // deopt the execution state and return to the interpreter.
1682   fr.deoptimize(thread);
1683 }
1684 
1685 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1686   // Deoptimize only if the frame comes from compile code.
1687   // Do not deoptimize the frame which is already patched
1688   // during the execution of the loops below.
1689   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1690     return;
1691   }
1692   ResourceMark rm;
1693   DeoptimizationMarker dm;
1694   deoptimize_single_frame(thread, fr, reason);
1695 }
1696 
1697 #if INCLUDE_JVMCI
1698 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {
1699   // there is no exception handler for this pc => deoptimize
1700   cm->make_not_entrant();
1701 
1702   // Use Deoptimization::deoptimize for all of its side-effects:
1703   // gathering traps statistics, logging...
1704   // it also patches the return pc but we do not care about that
1705   // since we return a continuation to the deopt_blob below.
1706   JavaThread* thread = JavaThread::current();
1707   RegisterMap reg_map(thread, false);
1708   frame runtime_frame = thread->last_frame();
1709   frame caller_frame = runtime_frame.sender(&reg_map);
1710   assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");
1711   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1712 
1713   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);
1714   if (trap_mdo != NULL) {
1715     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1716   }
1717 
1718   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1719 }
1720 #endif
1721 
1722 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1723   assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1724          "can only deoptimize other thread at a safepoint");
1725   // Compute frame and register map based on thread and sp.
1726   RegisterMap reg_map(thread, false);
1727   frame fr = thread->last_frame();
1728   while (fr.id() != id) {
1729     fr = fr.sender(&reg_map);
1730   }
1731   deoptimize(thread, fr, reason);
1732 }
1733 
1734 
1735 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1736   if (thread == Thread::current()) {
1737     Deoptimization::deoptimize_frame_internal(thread, id, reason);
1738   } else {
1739     VM_DeoptimizeFrame deopt(thread, id, reason);
1740     VMThread::execute(&deopt);
1741   }
1742 }
1743 
1744 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1745   deoptimize_frame(thread, id, Reason_constraint);
1746 }
1747 
1748 // JVMTI PopFrame support
1749 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1750 {
1751   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1752 }
1753 JRT_END
1754 
1755 MethodData*
1756 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1757                                 bool create_if_missing) {
1758   Thread* THREAD = thread;
1759   MethodData* mdo = m()->method_data();
1760   if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1761     // Build an MDO.  Ignore errors like OutOfMemory;
1762     // that simply means we won't have an MDO to update.
1763     Method::build_interpreter_method_data(m, THREAD);
1764     if (HAS_PENDING_EXCEPTION) {
1765       assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1766       CLEAR_PENDING_EXCEPTION;
1767     }
1768     mdo = m()->method_data();
1769   }
1770   return mdo;
1771 }
1772 
1773 #if COMPILER2_OR_JVMCI
1774 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1775   // In case of an unresolved klass entry, load the class.
1776   // This path is exercised from case _ldc in Parse::do_one_bytecode,
1777   // and probably nowhere else.
1778   // Even that case would benefit from simply re-interpreting the
1779   // bytecode, without paying special attention to the class index.
1780   // So this whole "class index" feature should probably be removed.
1781 
1782   if (constant_pool->tag_at(index).is_unresolved_klass()) {
1783     Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK);
1784     return;
1785   }
1786 
1787   assert(!constant_pool->tag_at(index).is_symbol(),
1788          "no symbolic names here, please");
1789 }
1790 
1791 
1792 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) {
1793   EXCEPTION_MARK;
1794   load_class_by_index(constant_pool, index, THREAD);
1795   if (HAS_PENDING_EXCEPTION) {
1796     // Exception happened during classloading. We ignore the exception here, since it
1797     // is going to be rethrown since the current activation is going to be deoptimized and
1798     // the interpreter will re-execute the bytecode.
1799     CLEAR_PENDING_EXCEPTION;
1800     // Class loading called java code which may have caused a stack
1801     // overflow. If the exception was thrown right before the return
1802     // to the runtime the stack is no longer guarded. Reguard the
1803     // stack otherwise if we return to the uncommon trap blob and the
1804     // stack bang causes a stack overflow we crash.
1805     assert(THREAD->is_Java_thread(), "only a java thread can be here");
1806     JavaThread* thread = (JavaThread*)THREAD;
1807     bool guard_pages_enabled = thread->stack_guards_enabled();
1808     if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
1809     assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1810   }
1811 }
1812 
1813 #if INCLUDE_JFR
1814 
1815 class DeoptReasonSerializer : public JfrSerializer {
1816  public:
1817   void serialize(JfrCheckpointWriter& writer) {
1818     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1819     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1820       writer.write_key((u8)i);
1821       writer.write(Deoptimization::trap_reason_name(i));
1822     }
1823   }
1824 };
1825 
1826 class DeoptActionSerializer : public JfrSerializer {
1827  public:
1828   void serialize(JfrCheckpointWriter& writer) {
1829     static const u4 nof_actions = Deoptimization::Action_LIMIT;
1830     writer.write_count(nof_actions);
1831     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1832       writer.write_key(i);
1833       writer.write(Deoptimization::trap_action_name((int)i));
1834     }
1835   }
1836 };
1837 
1838 static void register_serializers() {
1839   static int critical_section = 0;
1840   if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
1841     return;
1842   }
1843   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1844   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1845 }
1846 
1847 static void post_deoptimization_event(CompiledMethod* nm,
1848                                       const Method* method,
1849                                       int trap_bci,
1850                                       int instruction,
1851                                       Deoptimization::DeoptReason reason,
1852                                       Deoptimization::DeoptAction action) {
1853   assert(nm != NULL, "invariant");
1854   assert(method != NULL, "invariant");
1855   if (EventDeoptimization::is_enabled()) {
1856     static bool serializers_registered = false;
1857     if (!serializers_registered) {
1858       register_serializers();
1859       serializers_registered = true;
1860     }
1861     EventDeoptimization event;
1862     event.set_compileId(nm->compile_id());
1863     event.set_compiler(nm->compiler_type());
1864     event.set_method(method);
1865     event.set_lineNumber(method->line_number_from_bci(trap_bci));
1866     event.set_bci(trap_bci);
1867     event.set_instruction(instruction);
1868     event.set_reason(reason);
1869     event.set_action(action);
1870     event.commit();
1871   }
1872 }
1873 
1874 #endif // INCLUDE_JFR
1875 
1876 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1877   HandleMark hm;
1878 
1879   // uncommon_trap() is called at the beginning of the uncommon trap
1880   // handler. Note this fact before we start generating temporary frames
1881   // that can confuse an asynchronous stack walker. This counter is
1882   // decremented at the end of unpack_frames().
1883   thread->inc_in_deopt_handler();
1884 
1885   // We need to update the map if we have biased locking.
1886 #if INCLUDE_JVMCI
1887   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
1888   RegisterMap reg_map(thread, true);
1889 #else
1890   RegisterMap reg_map(thread, UseBiasedLocking);
1891 #endif
1892   frame stub_frame = thread->last_frame();
1893   frame fr = stub_frame.sender(&reg_map);
1894   // Make sure the calling nmethod is not getting deoptimized and removed
1895   // before we are done with it.
1896   nmethodLocker nl(fr.pc());
1897 
1898   // Log a message
1899   Events::log_deopt_message(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
1900               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
1901 
1902   {
1903     ResourceMark rm;
1904 
1905     DeoptReason reason = trap_request_reason(trap_request);
1906     DeoptAction action = trap_request_action(trap_request);
1907 #if INCLUDE_JVMCI
1908     int debug_id = trap_request_debug_id(trap_request);
1909 #endif
1910     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1911 
1912     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
1913     compiledVFrame* cvf = compiledVFrame::cast(vf);
1914 
1915     CompiledMethod* nm = cvf->code();
1916 
1917     ScopeDesc*      trap_scope  = cvf->scope();
1918 
1919     if (TraceDeoptimization) {
1920       ttyLocker ttyl;
1921       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
1922 #if INCLUDE_JVMCI
1923           , debug_id
1924 #endif
1925           );
1926     }
1927 
1928     methodHandle    trap_method(THREAD, trap_scope->method());
1929     int             trap_bci    = trap_scope->bci();
1930 #if INCLUDE_JVMCI
1931     jlong           speculation = thread->pending_failed_speculation();
1932     if (nm->is_compiled_by_jvmci() && nm->is_nmethod()) { // Exclude AOTed methods
1933       nm->as_nmethod()->update_speculation(thread);
1934     } else {
1935       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
1936     }
1937 
1938     if (trap_bci == SynchronizationEntryBCI) {
1939       trap_bci = 0;
1940       thread->set_pending_monitorenter(true);
1941     }
1942 
1943     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
1944       thread->set_pending_transfer_to_interpreter(true);
1945     }
1946 #endif
1947 
1948     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1949     // Record this event in the histogram.
1950     gather_statistics(reason, action, trap_bc);
1951 
1952     // Ensure that we can record deopt. history:
1953     // Need MDO to record RTM code generation state.
1954     bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );
1955 
1956     methodHandle profiled_method;
1957 #if INCLUDE_JVMCI
1958     if (nm->is_compiled_by_jvmci()) {
1959       profiled_method = methodHandle(THREAD, nm->method());
1960     } else {
1961       profiled_method = trap_method;
1962     }
1963 #else
1964     profiled_method = trap_method;
1965 #endif
1966 
1967     MethodData* trap_mdo =
1968       get_method_data(thread, profiled_method, create_if_missing);
1969 
1970     JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)
1971 
1972     // Log a message
1973     Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
1974                               trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),
1975                               trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
1976 
1977     // Print a bunch of diagnostics, if requested.
1978     if (TraceDeoptimization || LogCompilation) {
1979       ResourceMark rm;
1980       ttyLocker ttyl;
1981       char buf[100];
1982       if (xtty != NULL) {
1983         xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
1984                          os::current_thread_id(),
1985                          format_trap_request(buf, sizeof(buf), trap_request));
1986 #if INCLUDE_JVMCI
1987         if (speculation != 0) {
1988           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
1989         }
1990 #endif
1991         nm->log_identity(xtty);
1992       }
1993       Symbol* class_name = NULL;
1994       bool unresolved = false;
1995       if (unloaded_class_index >= 0) {
1996         constantPoolHandle constants (THREAD, trap_method->constants());
1997         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1998           class_name = constants->klass_name_at(unloaded_class_index);
1999           unresolved = true;
2000           if (xtty != NULL)
2001             xtty->print(" unresolved='1'");
2002         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
2003           class_name = constants->symbol_at(unloaded_class_index);
2004         }
2005         if (xtty != NULL)
2006           xtty->name(class_name);
2007       }
2008       if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {
2009         // Dump the relevant MDO state.
2010         // This is the deopt count for the current reason, any previous
2011         // reasons or recompiles seen at this point.
2012         int dcnt = trap_mdo->trap_count(reason);
2013         if (dcnt != 0)
2014           xtty->print(" count='%d'", dcnt);
2015         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
2016         int dos = (pdata == NULL)? 0: pdata->trap_state();
2017         if (dos != 0) {
2018           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
2019           if (trap_state_is_recompiled(dos)) {
2020             int recnt2 = trap_mdo->overflow_recompile_count();
2021             if (recnt2 != 0)
2022               xtty->print(" recompiles2='%d'", recnt2);
2023           }
2024         }
2025       }
2026       if (xtty != NULL) {
2027         xtty->stamp();
2028         xtty->end_head();
2029       }
2030       if (TraceDeoptimization) {  // make noise on the tty
2031         tty->print("Uncommon trap occurred in");
2032         nm->method()->print_short_name(tty);
2033         tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
2034 #if INCLUDE_JVMCI
2035         if (nm->is_nmethod()) {
2036           const char* installed_code_name = nm->as_nmethod()->jvmci_name();
2037           if (installed_code_name != NULL) {
2038             tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);
2039           }
2040         }
2041 #endif
2042         tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
2043                    p2i(fr.pc()),
2044                    os::current_thread_id(),
2045                    trap_reason_name(reason),
2046                    trap_action_name(action),
2047                    unloaded_class_index
2048 #if INCLUDE_JVMCI
2049                    , debug_id
2050 #endif
2051                    );
2052         if (class_name != NULL) {
2053           tty->print(unresolved ? " unresolved class: " : " symbol: ");
2054           class_name->print_symbol_on(tty);
2055         }
2056         tty->cr();
2057       }
2058       if (xtty != NULL) {
2059         // Log the precise location of the trap.
2060         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
2061           xtty->begin_elem("jvms bci='%d'", sd->bci());
2062           xtty->method(sd->method());
2063           xtty->end_elem();
2064           if (sd->is_top())  break;
2065         }
2066         xtty->tail("uncommon_trap");
2067       }
2068     }
2069     // (End diagnostic printout.)
2070 
2071     // Load class if necessary
2072     if (unloaded_class_index >= 0) {
2073       constantPoolHandle constants(THREAD, trap_method->constants());
2074       load_class_by_index(constants, unloaded_class_index);
2075     }
2076 
2077     // Flush the nmethod if necessary and desirable.
2078     //
2079     // We need to avoid situations where we are re-flushing the nmethod
2080     // because of a hot deoptimization site.  Repeated flushes at the same
2081     // point need to be detected by the compiler and avoided.  If the compiler
2082     // cannot avoid them (or has a bug and "refuses" to avoid them), this
2083     // module must take measures to avoid an infinite cycle of recompilation
2084     // and deoptimization.  There are several such measures:
2085     //
2086     //   1. If a recompilation is ordered a second time at some site X
2087     //   and for the same reason R, the action is adjusted to 'reinterpret',
2088     //   to give the interpreter time to exercise the method more thoroughly.
2089     //   If this happens, the method's overflow_recompile_count is incremented.
2090     //
2091     //   2. If the compiler fails to reduce the deoptimization rate, then
2092     //   the method's overflow_recompile_count will begin to exceed the set
2093     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
2094     //   is adjusted to 'make_not_compilable', and the method is abandoned
2095     //   to the interpreter.  This is a performance hit for hot methods,
2096     //   but is better than a disastrous infinite cycle of recompilations.
2097     //   (Actually, only the method containing the site X is abandoned.)
2098     //
2099     //   3. In parallel with the previous measures, if the total number of
2100     //   recompilations of a method exceeds the much larger set limit
2101     //   PerMethodRecompilationCutoff, the method is abandoned.
2102     //   This should only happen if the method is very large and has
2103     //   many "lukewarm" deoptimizations.  The code which enforces this
2104     //   limit is elsewhere (class nmethod, class Method).
2105     //
2106     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2107     // to recompile at each bytecode independently of the per-BCI cutoff.
2108     //
2109     // The decision to update code is up to the compiler, and is encoded
2110     // in the Action_xxx code.  If the compiler requests Action_none
2111     // no trap state is changed, no compiled code is changed, and the
2112     // computation suffers along in the interpreter.
2113     //
2114     // The other action codes specify various tactics for decompilation
2115     // and recompilation.  Action_maybe_recompile is the loosest, and
2116     // allows the compiled code to stay around until enough traps are seen,
2117     // and until the compiler gets around to recompiling the trapping method.
2118     //
2119     // The other actions cause immediate removal of the present code.
2120 
2121     // Traps caused by injected profile shouldn't pollute trap counts.
2122     bool injected_profile_trap = trap_method->has_injected_profile() &&
2123                                  (reason == Reason_intrinsic || reason == Reason_unreached);
2124 
2125     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2126     bool make_not_entrant = false;
2127     bool make_not_compilable = false;
2128     bool reprofile = false;
2129     switch (action) {
2130     case Action_none:
2131       // Keep the old code.
2132       update_trap_state = false;
2133       break;
2134     case Action_maybe_recompile:
2135       // Do not need to invalidate the present code, but we can
2136       // initiate another
2137       // Start compiler without (necessarily) invalidating the nmethod.
2138       // The system will tolerate the old code, but new code should be
2139       // generated when possible.
2140       break;
2141     case Action_reinterpret:
2142       // Go back into the interpreter for a while, and then consider
2143       // recompiling form scratch.
2144       make_not_entrant = true;
2145       // Reset invocation counter for outer most method.
2146       // This will allow the interpreter to exercise the bytecodes
2147       // for a while before recompiling.
2148       // By contrast, Action_make_not_entrant is immediate.
2149       //
2150       // Note that the compiler will track null_check, null_assert,
2151       // range_check, and class_check events and log them as if they
2152       // had been traps taken from compiled code.  This will update
2153       // the MDO trap history so that the next compilation will
2154       // properly detect hot trap sites.
2155       reprofile = true;
2156       break;
2157     case Action_make_not_entrant:
2158       // Request immediate recompilation, and get rid of the old code.
2159       // Make them not entrant, so next time they are called they get
2160       // recompiled.  Unloaded classes are loaded now so recompile before next
2161       // time they are called.  Same for uninitialized.  The interpreter will
2162       // link the missing class, if any.
2163       make_not_entrant = true;
2164       break;
2165     case Action_make_not_compilable:
2166       // Give up on compiling this method at all.
2167       make_not_entrant = true;
2168       make_not_compilable = true;
2169       break;
2170     default:
2171       ShouldNotReachHere();
2172     }
2173 
2174     // Setting +ProfileTraps fixes the following, on all platforms:
2175     // 4852688: ProfileInterpreter is off by default for ia64.  The result is
2176     // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2177     // recompile relies on a MethodData* to record heroic opt failures.
2178 
2179     // Whether the interpreter is producing MDO data or not, we also need
2180     // to use the MDO to detect hot deoptimization points and control
2181     // aggressive optimization.
2182     bool inc_recompile_count = false;
2183     ProfileData* pdata = NULL;
2184     if (ProfileTraps && !is_client_compilation_mode_vm() && update_trap_state && trap_mdo != NULL) {
2185       assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity");
2186       uint this_trap_count = 0;
2187       bool maybe_prior_trap = false;
2188       bool maybe_prior_recompile = false;
2189       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2190 #if INCLUDE_JVMCI
2191                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2192 #endif
2193                                    nm->method(),
2194                                    //outputs:
2195                                    this_trap_count,
2196                                    maybe_prior_trap,
2197                                    maybe_prior_recompile);
2198       // Because the interpreter also counts null, div0, range, and class
2199       // checks, these traps from compiled code are double-counted.
2200       // This is harmless; it just means that the PerXTrapLimit values
2201       // are in effect a little smaller than they look.
2202 
2203       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2204       if (per_bc_reason != Reason_none) {
2205         // Now take action based on the partially known per-BCI history.
2206         if (maybe_prior_trap
2207             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2208           // If there are too many traps at this BCI, force a recompile.
2209           // This will allow the compiler to see the limit overflow, and
2210           // take corrective action, if possible.  The compiler generally
2211           // does not use the exact PerBytecodeTrapLimit value, but instead
2212           // changes its tactics if it sees any traps at all.  This provides
2213           // a little hysteresis, delaying a recompile until a trap happens
2214           // several times.
2215           //
2216           // Actually, since there is only one bit of counter per BCI,
2217           // the possible per-BCI counts are {0,1,(per-method count)}.
2218           // This produces accurate results if in fact there is only
2219           // one hot trap site, but begins to get fuzzy if there are
2220           // many sites.  For example, if there are ten sites each
2221           // trapping two or more times, they each get the blame for
2222           // all of their traps.
2223           make_not_entrant = true;
2224         }
2225 
2226         // Detect repeated recompilation at the same BCI, and enforce a limit.
2227         if (make_not_entrant && maybe_prior_recompile) {
2228           // More than one recompile at this point.
2229           inc_recompile_count = maybe_prior_trap;
2230         }
2231       } else {
2232         // For reasons which are not recorded per-bytecode, we simply
2233         // force recompiles unconditionally.
2234         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2235         make_not_entrant = true;
2236       }
2237 
2238       // Go back to the compiler if there are too many traps in this method.
2239       if (this_trap_count >= per_method_trap_limit(reason)) {
2240         // If there are too many traps in this method, force a recompile.
2241         // This will allow the compiler to see the limit overflow, and
2242         // take corrective action, if possible.
2243         // (This condition is an unlikely backstop only, because the
2244         // PerBytecodeTrapLimit is more likely to take effect first,
2245         // if it is applicable.)
2246         make_not_entrant = true;
2247       }
2248 
2249       // Here's more hysteresis:  If there has been a recompile at
2250       // this trap point already, run the method in the interpreter
2251       // for a while to exercise it more thoroughly.
2252       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2253         reprofile = true;
2254       }
2255     }
2256 
2257     // Take requested actions on the method:
2258 
2259     // Recompile
2260     if (make_not_entrant) {
2261       if (!nm->make_not_entrant()) {
2262         return; // the call did not change nmethod's state
2263       }
2264 
2265       if (pdata != NULL) {
2266         // Record the recompilation event, if any.
2267         int tstate0 = pdata->trap_state();
2268         int tstate1 = trap_state_set_recompiled(tstate0, true);
2269         if (tstate1 != tstate0)
2270           pdata->set_trap_state(tstate1);
2271       }
2272 
2273 #if INCLUDE_RTM_OPT
2274       // Restart collecting RTM locking abort statistic if the method
2275       // is recompiled for a reason other than RTM state change.
2276       // Assume that in new recompiled code the statistic could be different,
2277       // for example, due to different inlining.
2278       if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
2279           UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {
2280         trap_mdo->atomic_set_rtm_state(ProfileRTM);
2281       }
2282 #endif
2283       // For code aging we count traps separately here, using make_not_entrant()
2284       // as a guard against simultaneous deopts in multiple threads.
2285       if (reason == Reason_tenured && trap_mdo != NULL) {
2286         trap_mdo->inc_tenure_traps();
2287       }
2288     }
2289 
2290     if (inc_recompile_count) {
2291       trap_mdo->inc_overflow_recompile_count();
2292       if ((uint)trap_mdo->overflow_recompile_count() >
2293           (uint)PerBytecodeRecompilationCutoff) {
2294         // Give up on the method containing the bad BCI.
2295         if (trap_method() == nm->method()) {
2296           make_not_compilable = true;
2297         } else {
2298           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2299           // But give grace to the enclosing nm->method().
2300         }
2301       }
2302     }
2303 
2304     // Reprofile
2305     if (reprofile) {
2306       CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
2307     }
2308 
2309     // Give up compiling
2310     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2311       assert(make_not_entrant, "consistent");
2312       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2313     }
2314 
2315   } // Free marked resources
2316 
2317 }
2318 JRT_END
2319 
2320 ProfileData*
2321 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2322                                          int trap_bci,
2323                                          Deoptimization::DeoptReason reason,
2324                                          bool update_total_trap_count,
2325 #if INCLUDE_JVMCI
2326                                          bool is_osr,
2327 #endif
2328                                          Method* compiled_method,
2329                                          //outputs:
2330                                          uint& ret_this_trap_count,
2331                                          bool& ret_maybe_prior_trap,
2332                                          bool& ret_maybe_prior_recompile) {
2333   bool maybe_prior_trap = false;
2334   bool maybe_prior_recompile = false;
2335   uint this_trap_count = 0;
2336   if (update_total_trap_count) {
2337     uint idx = reason;
2338 #if INCLUDE_JVMCI
2339     if (is_osr) {
2340       idx += Reason_LIMIT;
2341     }
2342 #endif
2343     uint prior_trap_count = trap_mdo->trap_count(idx);
2344     this_trap_count  = trap_mdo->inc_trap_count(idx);
2345 
2346     // If the runtime cannot find a place to store trap history,
2347     // it is estimated based on the general condition of the method.
2348     // If the method has ever been recompiled, or has ever incurred
2349     // a trap with the present reason , then this BCI is assumed
2350     // (pessimistically) to be the culprit.
2351     maybe_prior_trap      = (prior_trap_count != 0);
2352     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2353   }
2354   ProfileData* pdata = NULL;
2355 
2356 
2357   // For reasons which are recorded per bytecode, we check per-BCI data.
2358   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2359   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2360   if (per_bc_reason != Reason_none) {
2361     // Find the profile data for this BCI.  If there isn't one,
2362     // try to allocate one from the MDO's set of spares.
2363     // This will let us detect a repeated trap at this point.
2364     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
2365 
2366     if (pdata != NULL) {
2367       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2368         if (LogCompilation && xtty != NULL) {
2369           ttyLocker ttyl;
2370           // no more room for speculative traps in this MDO
2371           xtty->elem("speculative_traps_oom");
2372         }
2373       }
2374       // Query the trap state of this profile datum.
2375       int tstate0 = pdata->trap_state();
2376       if (!trap_state_has_reason(tstate0, per_bc_reason))
2377         maybe_prior_trap = false;
2378       if (!trap_state_is_recompiled(tstate0))
2379         maybe_prior_recompile = false;
2380 
2381       // Update the trap state of this profile datum.
2382       int tstate1 = tstate0;
2383       // Record the reason.
2384       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2385       // Store the updated state on the MDO, for next time.
2386       if (tstate1 != tstate0)
2387         pdata->set_trap_state(tstate1);
2388     } else {
2389       if (LogCompilation && xtty != NULL) {
2390         ttyLocker ttyl;
2391         // Missing MDP?  Leave a small complaint in the log.
2392         xtty->elem("missing_mdp bci='%d'", trap_bci);
2393       }
2394     }
2395   }
2396 
2397   // Return results:
2398   ret_this_trap_count = this_trap_count;
2399   ret_maybe_prior_trap = maybe_prior_trap;
2400   ret_maybe_prior_recompile = maybe_prior_recompile;
2401   return pdata;
2402 }
2403 
2404 void
2405 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2406   ResourceMark rm;
2407   // Ignored outputs:
2408   uint ignore_this_trap_count;
2409   bool ignore_maybe_prior_trap;
2410   bool ignore_maybe_prior_recompile;
2411   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2412   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2413   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2414   query_update_method_data(trap_mdo, trap_bci,
2415                            (DeoptReason)reason,
2416                            update_total_counts,
2417 #if INCLUDE_JVMCI
2418                            false,
2419 #endif
2420                            NULL,
2421                            ignore_this_trap_count,
2422                            ignore_maybe_prior_trap,
2423                            ignore_maybe_prior_recompile);
2424 }
2425 
2426 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) {
2427   if (TraceDeoptimization) {
2428     tty->print("Uncommon trap ");
2429   }
2430   // Still in Java no safepoints
2431   {
2432     // This enters VM and may safepoint
2433     uncommon_trap_inner(thread, trap_request);
2434   }
2435   return fetch_unroll_info_helper(thread, exec_mode);
2436 }
2437 
2438 // Local derived constants.
2439 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2440 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2441 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2442 
2443 //---------------------------trap_state_reason---------------------------------
2444 Deoptimization::DeoptReason
2445 Deoptimization::trap_state_reason(int trap_state) {
2446   // This assert provides the link between the width of DataLayout::trap_bits
2447   // and the encoding of "recorded" reasons.  It ensures there are enough
2448   // bits to store all needed reasons in the per-BCI MDO profile.
2449   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2450   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2451   trap_state -= recompile_bit;
2452   if (trap_state == DS_REASON_MASK) {
2453     return Reason_many;
2454   } else {
2455     assert((int)Reason_none == 0, "state=0 => Reason_none");
2456     return (DeoptReason)trap_state;
2457   }
2458 }
2459 //-------------------------trap_state_has_reason-------------------------------
2460 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2461   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2462   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2463   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2464   trap_state -= recompile_bit;
2465   if (trap_state == DS_REASON_MASK) {
2466     return -1;  // true, unspecifically (bottom of state lattice)
2467   } else if (trap_state == reason) {
2468     return 1;   // true, definitely
2469   } else if (trap_state == 0) {
2470     return 0;   // false, definitely (top of state lattice)
2471   } else {
2472     return 0;   // false, definitely
2473   }
2474 }
2475 //-------------------------trap_state_add_reason-------------------------------
2476 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2477   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2478   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2479   trap_state -= recompile_bit;
2480   if (trap_state == DS_REASON_MASK) {
2481     return trap_state + recompile_bit;     // already at state lattice bottom
2482   } else if (trap_state == reason) {
2483     return trap_state + recompile_bit;     // the condition is already true
2484   } else if (trap_state == 0) {
2485     return reason + recompile_bit;          // no condition has yet been true
2486   } else {
2487     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2488   }
2489 }
2490 //-----------------------trap_state_is_recompiled------------------------------
2491 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2492   return (trap_state & DS_RECOMPILE_BIT) != 0;
2493 }
2494 //-----------------------trap_state_set_recompiled-----------------------------
2495 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2496   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2497   else    return trap_state & ~DS_RECOMPILE_BIT;
2498 }
2499 //---------------------------format_trap_state---------------------------------
2500 // This is used for debugging and diagnostics, including LogFile output.
2501 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2502                                               int trap_state) {
2503   assert(buflen > 0, "sanity");
2504   DeoptReason reason      = trap_state_reason(trap_state);
2505   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2506   // Re-encode the state from its decoded components.
2507   int decoded_state = 0;
2508   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2509     decoded_state = trap_state_add_reason(decoded_state, reason);
2510   if (recomp_flag)
2511     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2512   // If the state re-encodes properly, format it symbolically.
2513   // Because this routine is used for debugging and diagnostics,
2514   // be robust even if the state is a strange value.
2515   size_t len;
2516   if (decoded_state != trap_state) {
2517     // Random buggy state that doesn't decode??
2518     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2519   } else {
2520     len = jio_snprintf(buf, buflen, "%s%s",
2521                        trap_reason_name(reason),
2522                        recomp_flag ? " recompiled" : "");
2523   }
2524   return buf;
2525 }
2526 
2527 
2528 //--------------------------------statics--------------------------------------
2529 const char* Deoptimization::_trap_reason_name[] = {
2530   // Note:  Keep this in sync. with enum DeoptReason.
2531   "none",
2532   "null_check",
2533   "null_assert" JVMCI_ONLY("_or_unreached0"),
2534   "range_check",
2535   "class_check",
2536   "array_check",
2537   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2538   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2539   "profile_predicate",
2540   "unloaded",
2541   "uninitialized",
2542   "initialized",
2543   "unreached",
2544   "unhandled",
2545   "constraint",
2546   "div0_check",
2547   "age",
2548   "predicate",
2549   "loop_limit_check",
2550   "speculate_class_check",
2551   "speculate_null_check",
2552   "speculate_null_assert",
2553   "rtm_state_change",
2554   "unstable_if",
2555   "unstable_fused_if",
2556 #if INCLUDE_JVMCI
2557   "aliasing",
2558   "transfer_to_interpreter",
2559   "not_compiled_exception_handler",
2560   "unresolved",
2561   "jsr_mismatch",
2562 #endif
2563   "tenured"
2564 };
2565 const char* Deoptimization::_trap_action_name[] = {
2566   // Note:  Keep this in sync. with enum DeoptAction.
2567   "none",
2568   "maybe_recompile",
2569   "reinterpret",
2570   "make_not_entrant",
2571   "make_not_compilable"
2572 };
2573 
2574 const char* Deoptimization::trap_reason_name(int reason) {
2575   // Check that every reason has a name
2576   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2577 
2578   if (reason == Reason_many)  return "many";
2579   if ((uint)reason < Reason_LIMIT)
2580     return _trap_reason_name[reason];
2581   static char buf[20];
2582   sprintf(buf, "reason%d", reason);
2583   return buf;
2584 }
2585 const char* Deoptimization::trap_action_name(int action) {
2586   // Check that every action has a name
2587   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2588 
2589   if ((uint)action < Action_LIMIT)
2590     return _trap_action_name[action];
2591   static char buf[20];
2592   sprintf(buf, "action%d", action);
2593   return buf;
2594 }
2595 
2596 // This is used for debugging and diagnostics, including LogFile output.
2597 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2598                                                 int trap_request) {
2599   jint unloaded_class_index = trap_request_index(trap_request);
2600   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2601   const char* action = trap_action_name(trap_request_action(trap_request));
2602 #if INCLUDE_JVMCI
2603   int debug_id = trap_request_debug_id(trap_request);
2604 #endif
2605   size_t len;
2606   if (unloaded_class_index < 0) {
2607     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2608                        reason, action
2609 #if INCLUDE_JVMCI
2610                        ,debug_id
2611 #endif
2612                        );
2613   } else {
2614     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2615                        reason, action, unloaded_class_index
2616 #if INCLUDE_JVMCI
2617                        ,debug_id
2618 #endif
2619                        );
2620   }
2621   return buf;
2622 }
2623 
2624 juint Deoptimization::_deoptimization_hist
2625         [Deoptimization::Reason_LIMIT]
2626     [1 + Deoptimization::Action_LIMIT]
2627         [Deoptimization::BC_CASE_LIMIT]
2628   = {0};
2629 
2630 enum {
2631   LSB_BITS = 8,
2632   LSB_MASK = right_n_bits(LSB_BITS)
2633 };
2634 
2635 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2636                                        Bytecodes::Code bc) {
2637   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2638   assert(action >= 0 && action < Action_LIMIT, "oob");
2639   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2640   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2641   juint* cases = _deoptimization_hist[reason][1+action];
2642   juint* bc_counter_addr = NULL;
2643   juint  bc_counter      = 0;
2644   // Look for an unused counter, or an exact match to this BC.
2645   if (bc != Bytecodes::_illegal) {
2646     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2647       juint* counter_addr = &cases[bc_case];
2648       juint  counter = *counter_addr;
2649       if ((counter == 0 && bc_counter_addr == NULL)
2650           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2651         // this counter is either free or is already devoted to this BC
2652         bc_counter_addr = counter_addr;
2653         bc_counter = counter | bc;
2654       }
2655     }
2656   }
2657   if (bc_counter_addr == NULL) {
2658     // Overflow, or no given bytecode.
2659     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2660     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2661   }
2662   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2663 }
2664 
2665 jint Deoptimization::total_deoptimization_count() {
2666   return _deoptimization_hist[Reason_none][0][0];
2667 }
2668 
2669 void Deoptimization::print_statistics() {
2670   juint total = total_deoptimization_count();
2671   juint account = total;
2672   if (total != 0) {
2673     ttyLocker ttyl;
2674     if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
2675     tty->print_cr("Deoptimization traps recorded:");
2676     #define PRINT_STAT_LINE(name, r) \
2677       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2678     PRINT_STAT_LINE("total", total);
2679     // For each non-zero entry in the histogram, print the reason,
2680     // the action, and (if specifically known) the type of bytecode.
2681     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2682       for (int action = 0; action < Action_LIMIT; action++) {
2683         juint* cases = _deoptimization_hist[reason][1+action];
2684         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2685           juint counter = cases[bc_case];
2686           if (counter != 0) {
2687             char name[1*K];
2688             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2689             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2690               bc = Bytecodes::_illegal;
2691             sprintf(name, "%s/%s/%s",
2692                     trap_reason_name(reason),
2693                     trap_action_name(action),
2694                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2695             juint r = counter >> LSB_BITS;
2696             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2697             account -= r;
2698           }
2699         }
2700       }
2701     }
2702     if (account != 0) {
2703       PRINT_STAT_LINE("unaccounted", account);
2704     }
2705     #undef PRINT_STAT_LINE
2706     if (xtty != NULL)  xtty->tail("statistics");
2707   }
2708 }
2709 
2710 #ifdef ASSERT
2711 // Revert optimizations based on escape analysis.
2712 void Deoptimization::deoptimize_objects_alot_loop() {
2713   JavaThread* ct = JavaThread::current();
2714   HandleMark hm(ct);
2715   if (DeoptimizeObjectsALotThreadCount == 1) {
2716     // Revert everything at once
2717     while (!ct->is_terminated()) {
2718       { // Begin new scope for escape barrier
2719         HandleMarkCleaner hmc(ct);
2720         ResourceMark rm(ct);
2721         EscapeBarrier eb(ct, true);
2722         eb.deoptimize_objects_all_threads();
2723       }
2724       // Now sleep after the escape barriers destructor resumed the java threads.
2725       ct->sleep(DeoptimizeObjectsALotInterval);
2726     }
2727   } else {
2728     // Revert everything for one deoptee_thread which gets selected round robin
2729     JavaThread* deoptee_thread = NULL;
2730     while (!ct->is_terminated()) {
2731       { // Begin new scope for escape barrier
2732         HandleMarkCleaner hmc(ct);
2733         ResourceMark rm(ct);
2734         ThreadsListHandle tlh;
2735         int idx = (1 + tlh.list()->find_index_of_JavaThread(deoptee_thread)) % tlh.list()->length();
2736         deoptee_thread = tlh.list()->thread_at(idx);
2737         EscapeBarrier eb(ct, deoptee_thread, true);
2738         eb.deoptimize_objects(100);
2739       }
2740       // Now sleep after the escape barriers destructor resumed deoptee_thread.
2741       ct->sleep(DeoptimizeObjectsALotInterval);
2742     }
2743   }
2744 }
2745 #endif // !ASSERT
2746 
2747 // Returns true iff objects were reallocated and relocked because of access through JVMTI
2748 bool EscapeBarrier::objs_are_deoptimized(JavaThread* thread, intptr_t* fr_id) {
2749   // first/oldest update holds the flag
2750   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread);
2751   bool result = false;
2752   if (list != NULL) {
2753     for (int i = 0; i < list->length(); i++) {
2754       if (list->at(i)->matches(fr_id)) {
2755         result = list->at(i)->objects_are_deoptimized();
2756         break;
2757       }
2758     }
2759   }
2760   return result;
2761 }
2762 
2763 // Deoptimize frames with non escaping objects. Deoptimize objects with optimizations based on
2764 // escape analysis. Do it for all frames within the given depth and continue from there until the
2765 // entry frame is reached, because thread local objects passed as arguments might escape from callee
2766 // frames within the given depth.
2767 bool EscapeBarrier::deoptimize_objects(int depth) {
2768   if (barrier_active() && deoptee_thread()->has_last_Java_frame()) {
2769     ResourceMark rm(calling_thread());
2770     HandleMark   hm;
2771     RegisterMap  reg_map(deoptee_thread());
2772     vframe* vf = deoptee_thread()->last_java_vframe(&reg_map);
2773     int cur_depth = 0;
2774     while (vf != NULL && ((cur_depth <= depth) || !vf->is_entry_frame())) {
2775       if (vf->is_compiled_frame()) {
2776         compiledVFrame* cvf = compiledVFrame::cast(vf);
2777         // Deoptimize frame and local objects if any exist.
2778         // If cvf is deeper than depth, then we deoptimize iff local objects are passed as args.
2779         bool should_deopt = cur_depth <= depth ? cvf->not_global_escape_in_scope() : cvf->arg_escape();
2780         if (should_deopt && !deoptimize_objects(cvf->fr().id())) {
2781           // reallocation of scalar replaced objects failed, because heap is exhausted
2782           return false;
2783         }
2784       }
2785 
2786       // move to next physical frame
2787       while(!vf->is_top()) {
2788         cur_depth++;
2789         vf = vf->sender();
2790       }
2791       cur_depth++;
2792       vf = vf->sender();
2793     }
2794   }
2795   return true;
2796 }
2797 
2798 bool EscapeBarrier::deoptimize_objects_all_threads() {
2799   if (!barrier_active()) return true;
2800   ResourceMark rm(calling_thread());
2801   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2802     if (jt->has_last_Java_frame()) {
2803       RegisterMap reg_map(jt);
2804       vframe* vf = jt->last_java_vframe(&reg_map);
2805       assert(jt->frame_anchor()->walkable(),
2806              "The stack of JavaThread " PTR_FORMAT " is not walkable. Thread state is %d",
2807              p2i(jt), jt->thread_state());
2808       while (vf != NULL) {
2809         if (vf->is_compiled_frame()) {
2810           compiledVFrame* cvf = compiledVFrame::cast(vf);
2811           if ((cvf->not_global_escape_in_scope() || cvf->arg_escape()) &&
2812               !deoptimize_objects_internal(jt, cvf->fr().id())) {
2813             return false; // reallocation failure
2814           }
2815         }
2816         // move to next physical frame
2817         while(!vf->is_top()) {
2818           vf = vf->sender();
2819         }
2820         vf = vf->sender();
2821       }
2822     }
2823   }
2824   return true; // success
2825 }
2826 
2827 bool EscapeBarrier::_deoptimizing_objects_for_all_threads = false;
2828 bool EscapeBarrier::_self_deoptimization_in_progress      = false;
2829 
2830 class EscapeBarrierSuspendHandshake : public HandshakeClosure {
2831   JavaThread* _excluded_thread;
2832  public:
2833   EscapeBarrierSuspendHandshake(JavaThread* excluded_thread, const char* name) : HandshakeClosure(name), _excluded_thread(excluded_thread) { }
2834   void do_thread(Thread* th) {
2835     if (th->is_Java_thread() && !th->is_hidden_from_external_view() && (th != _excluded_thread)) {
2836       th->set_ea_obj_deopt_flag();
2837     }
2838   }
2839 };
2840 
2841 void EscapeBarrier::sync_and_suspend_one() {
2842   assert(_calling_thread != NULL, "calling thread must not be NULL");
2843   assert(_deoptee_thread != NULL, "deoptee thread must not be NULL");
2844   assert(barrier_active(), "should not call");
2845 
2846   // Sync with other threads that might be doing deoptimizations
2847   {
2848     // Need to switch to _thread_blocked for the wait() call
2849     ThreadBlockInVM tbivm(_calling_thread);
2850     MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
2851     while (_self_deoptimization_in_progress || _deoptee_thread->is_ea_obj_deopt_suspend()) {
2852       ml.wait();
2853     }
2854 
2855     if (self_deopt()) {
2856       _self_deoptimization_in_progress = true;
2857       return;
2858     }
2859 
2860     // set suspend flag for target thread
2861     _deoptee_thread->set_ea_obj_deopt_flag();
2862   }
2863 
2864   // suspend target thread
2865   uint32_t debug_bits = 0;
2866   if (!_deoptee_thread->is_thread_fully_suspended(false, &debug_bits)) {
2867     EscapeBarrierSuspendHandshake sh(NULL, "EscapeBarrierSuspendOne");
2868     Handshake::execute(&sh, _deoptee_thread);
2869   }
2870   assert(!_deoptee_thread->has_last_Java_frame() || _deoptee_thread->frame_anchor()->walkable(),
2871          "stack should be walkable now");
2872 }
2873 
2874 void EscapeBarrier::sync_and_suspend_all() {
2875   assert(barrier_active(), "should not call");
2876   assert(_calling_thread != NULL, "calling thread must not be NULL");
2877   assert(all_threads(), "sanity");
2878 
2879   // Sync with other threads that might be doing deoptimizations
2880   {
2881     // Need to switch to _thread_blocked for the wait() call
2882     ThreadBlockInVM tbivm(_calling_thread);
2883     MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
2884 
2885     bool deopt_in_progress;
2886     do {
2887       deopt_in_progress = _self_deoptimization_in_progress;
2888       for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2889         deopt_in_progress = (deopt_in_progress || jt->is_ea_obj_deopt_suspend());
2890         if (deopt_in_progress) {
2891           break;
2892         }
2893       }
2894       if (deopt_in_progress) {
2895         ml.wait(); // then check again
2896       }
2897     } while(deopt_in_progress);
2898 
2899     _self_deoptimization_in_progress = true;
2900     _deoptimizing_objects_for_all_threads = true;
2901   }
2902 
2903   EscapeBarrierSuspendHandshake sh(_calling_thread, "EscapeBarrierSuspendAll");
2904   Handshake::execute(&sh);
2905 #ifdef ASSERT
2906   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2907     if (jt->is_hidden_from_external_view()) continue;
2908     assert(!jt->has_last_Java_frame() || jt->frame_anchor()->walkable(),
2909            "The stack of JavaThread " PTR_FORMAT " is not walkable. Thread state is %d",
2910            p2i(jt), jt->thread_state());
2911   }
2912 #endif // ASSERT
2913 }
2914 
2915 void EscapeBarrier::resume_one() {
2916   assert(barrier_active(), "should not call");
2917   assert(!all_threads(), "use resume_all()");
2918   MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
2919   if (self_deopt()) {
2920     assert(_self_deoptimization_in_progress, "incorrect synchronization");
2921     _self_deoptimization_in_progress = false;
2922   } else {
2923     _deoptee_thread->clear_ea_obj_deopt_flag();
2924   }
2925   ml.notify_all();
2926 }
2927 
2928 void EscapeBarrier::resume_all() {
2929   assert(barrier_active(), "should not call");
2930   assert(all_threads(), "use resume_one()");
2931   MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
2932   assert(_self_deoptimization_in_progress, "incorrect synchronization");
2933   _deoptimizing_objects_for_all_threads = false;
2934   _self_deoptimization_in_progress = false;
2935   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2936     jt->clear_ea_obj_deopt_flag();
2937   }
2938   ml.notify_all();
2939 }
2940 
2941 void EscapeBarrier::thread_added(JavaThread* jt) {
2942   if (!jt->is_hidden_from_external_view()) {
2943     MutexLocker ml(EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
2944     if (_deoptimizing_objects_for_all_threads) {
2945       jt->set_ea_obj_deopt_flag();
2946     } else {
2947       jt->clear_ea_obj_deopt_flag();
2948     }
2949   }
2950 }
2951 
2952 // Remember that objects were reallocated and relocked for the compiled frame with the given id
2953 static void set_objs_are_deoptimized(JavaThread* thread, intptr_t* fr_id) {
2954   // set in first/oldest update
2955   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread);
2956   DEBUG_ONLY(bool found = false);
2957   if (list != NULL) {
2958     for (int i = 0; i < list->length(); i++) {
2959       if (list->at(i)->matches(fr_id)) {
2960         DEBUG_ONLY(found = true);
2961         list->at(i)->set_objs_are_deoptimized();
2962         break;
2963       }
2964     }
2965   }
2966   assert(found, "variable set should exist at least for one vframe");
2967 }
2968 
2969 // Deoptimize the given frame and deoptimize objects with optimizations based on escape analysis,
2970 // i.e. reallocate scalar replaced objects on the heap and relock objects if locking has been
2971 // eliminated.
2972 // Deoptimized objects are kept as JVMTI deferred updates until the compiled frame is replaced with interpreter frames.
2973 // Returns false iff at least one reallocation failed.
2974 bool EscapeBarrier::deoptimize_objects_internal(JavaThread* deoptee, intptr_t* fr_id) {
2975   if (!barrier_active()) return true;
2976 
2977   JavaThread* ct = calling_thread();
2978   bool realloc_failures = false;
2979 
2980   if (!objs_are_deoptimized(deoptee, fr_id)) {
2981     // Make sure the frame identified by fr_id is deoptimized and fetch its last vframe
2982     compiledVFrame* last_cvf;
2983     bool fr_is_deoptimized;
2984     do {
2985       StackFrameStream fst(deoptee);
2986       while (fst.current()->id() != fr_id && !fst.is_done()) {
2987         fst.next();
2988       }
2989       assert(fst.current()->id() == fr_id, "frame not found");
2990       assert(fst.current()->is_compiled_frame(), "only compiled frames can contain stack allocated objects");
2991       fr_is_deoptimized = fst.current()->is_deoptimized_frame();
2992       if (!fr_is_deoptimized) {
2993         // Execution must not continue in the compiled method, so we deoptimize the frame.
2994         Deoptimization::deoptimize_frame(deoptee, fr_id);
2995       } else {
2996         last_cvf = compiledVFrame::cast(vframe::new_vframe(fst.current(), fst.register_map(), deoptee));
2997       }
2998     } while(!fr_is_deoptimized);
2999 
3000     // collect inlined frames
3001     compiledVFrame* cvf = last_cvf;
3002     GrowableArray<compiledVFrame*>* vfs = new GrowableArray<compiledVFrame*>(10);
3003     while (!cvf->is_top()) {
3004       vfs->push(cvf);
3005       cvf = compiledVFrame::cast(cvf->sender());
3006     }
3007     vfs->push(cvf);
3008 
3009     // reallocate and relock optimized objects
3010     bool deoptimized_objects = Deoptimization::deoptimize_objects_internal(ct, vfs, realloc_failures);
3011     if (!realloc_failures && deoptimized_objects) {
3012       // now do the updates
3013       for (int frame_index = 0; frame_index < vfs->length(); frame_index++) {
3014         cvf = vfs->at(frame_index);
3015 
3016         // locals
3017         GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals();
3018         StackValueCollection* locals = cvf->locals();
3019         if (locals != NULL) {
3020           for (int i2 = 0; i2 < locals->size(); i2++) {
3021             StackValue* var = locals->at(i2);
3022             if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) {
3023               jvalue val;
3024               val.l = cast_from_oop<jobject>(locals->at(i2)->get_obj()());
3025               cvf->update_local(T_OBJECT, i2, val);
3026             }
3027           }
3028         }
3029 
3030         // expressions
3031         GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions();
3032         StackValueCollection* expressions = cvf->expressions();
3033         if (expressions != NULL) {
3034           for (int i2 = 0; i2 < expressions->size(); i2++) {
3035             StackValue* var = expressions->at(i2);
3036             if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) {
3037               jvalue val;
3038               val.l = cast_from_oop<jobject>(expressions->at(i2)->get_obj()());
3039               cvf->update_stack(T_OBJECT, i2, val);
3040             }
3041           }
3042         }
3043 
3044         // monitors
3045         GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
3046         if (monitors != NULL) {
3047           for (int i2 = 0; i2 < monitors->length(); i2++) {
3048             if (monitors->at(i2)->eliminated()) {
3049               assert(!monitors->at(i2)->owner_is_scalar_replaced(), "reallocation failure, should not update");
3050               cvf->update_monitor(i2, monitors->at(i2));
3051             }
3052           }
3053         }
3054       }
3055       set_objs_are_deoptimized(deoptee, fr_id);
3056     }
3057   }
3058   return !realloc_failures;
3059 }
3060 
3061 #else // COMPILER2_OR_JVMCI
3062 
3063 
3064 // Stubs for C1 only system.
3065 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
3066   return false;
3067 }
3068 
3069 const char* Deoptimization::trap_reason_name(int reason) {
3070   return "unknown";
3071 }
3072 
3073 void Deoptimization::print_statistics() {
3074   // no output
3075 }
3076 
3077 void
3078 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
3079   // no udpate
3080 }
3081 
3082 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
3083   return 0;
3084 }
3085 
3086 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
3087                                        Bytecodes::Code bc) {
3088   // no update
3089 }
3090 
3091 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
3092                                               int trap_state) {
3093   jio_snprintf(buf, buflen, "#%d", trap_state);
3094   return buf;
3095 }
3096 
3097 #endif // COMPILER2_OR_JVMCI