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