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