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