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