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