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