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