1 /*
   2  * Copyright (c) 1997, 2021, 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 "jvm.h"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "classfile/vmClasses.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/debugInfoRec.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "gc/shared/collectedHeap.hpp"
  38 #include "interpreter/bytecode.hpp"
  39 #include "interpreter/interpreter.hpp"
  40 #include "interpreter/oopMapCache.hpp"
  41 #include "memory/allocation.inline.hpp"
  42 #include "memory/oopFactory.hpp"
  43 #include "memory/resourceArea.hpp"
  44 #include "memory/universe.hpp"
  45 #include "oops/constantPool.hpp"


  46 #include "oops/method.hpp"
  47 #include "oops/objArrayKlass.hpp"
  48 #include "oops/objArrayOop.inline.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/fieldStreams.inline.hpp"

  51 #include "oops/typeArrayOop.inline.hpp"
  52 #include "oops/verifyOopClosure.hpp"
  53 #include "prims/jvmtiDeferredUpdates.hpp"
  54 #include "prims/jvmtiExport.hpp"
  55 #include "prims/jvmtiThreadState.hpp"
  56 #include "prims/vectorSupport.hpp"
  57 #include "prims/methodHandles.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/deoptimization.hpp"
  60 #include "runtime/escapeBarrier.hpp"
  61 #include "runtime/fieldDescriptor.hpp"
  62 #include "runtime/fieldDescriptor.inline.hpp"
  63 #include "runtime/frame.inline.hpp"
  64 #include "runtime/handles.inline.hpp"
  65 #include "runtime/interfaceSupport.inline.hpp"
  66 #include "runtime/jniHandles.inline.hpp"
  67 #include "runtime/keepStackGCProcessed.hpp"
  68 #include "runtime/objectMonitor.inline.hpp"
  69 #include "runtime/osThread.hpp"
  70 #include "runtime/safepointVerifiers.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/signature.hpp"
  73 #include "runtime/stackFrameStream.inline.hpp"
  74 #include "runtime/stackWatermarkSet.hpp"
  75 #include "runtime/stubRoutines.hpp"
  76 #include "runtime/thread.hpp"
  77 #include "runtime/threadSMR.hpp"
  78 #include "runtime/threadWXSetters.inline.hpp"
  79 #include "runtime/vframe.hpp"
  80 #include "runtime/vframeArray.hpp"
  81 #include "runtime/vframe_hp.hpp"
  82 #include "runtime/vmOperations.hpp"
  83 #include "utilities/events.hpp"
  84 #include "utilities/macros.hpp"
  85 #include "utilities/preserveException.hpp"
  86 #include "utilities/xmlstream.hpp"
  87 #if INCLUDE_JFR
  88 #include "jfr/jfrEvents.hpp"
  89 #include "jfr/metadata/jfrSerializer.hpp"
  90 #endif
  91 
  92 bool DeoptimizationMarker::_is_active = false;
  93 
  94 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
  95                                          int  caller_adjustment,
  96                                          int  caller_actual_parameters,
  97                                          int  number_of_frames,
  98                                          intptr_t* frame_sizes,
  99                                          address* frame_pcs,
 100                                          BasicType return_type,
 101                                          int exec_mode) {
 102   _size_of_deoptimized_frame = size_of_deoptimized_frame;
 103   _caller_adjustment         = caller_adjustment;
 104   _caller_actual_parameters  = caller_actual_parameters;
 105   _number_of_frames          = number_of_frames;
 106   _frame_sizes               = frame_sizes;
 107   _frame_pcs                 = frame_pcs;
 108   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
 109   _return_type               = return_type;
 110   _initial_info              = 0;
 111   // PD (x86 only)
 112   _counter_temp              = 0;
 113   _unpack_kind               = exec_mode;
 114   _sender_sp_temp            = 0;
 115 
 116   _total_frame_sizes         = size_of_frames();
 117   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 118 }
 119 
 120 
 121 Deoptimization::UnrollBlock::~UnrollBlock() {
 122   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
 123   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
 124   FREE_C_HEAP_ARRAY(intptr_t, _register_block);
 125 }
 126 
 127 
 128 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
 129   assert(register_number < RegisterMap::reg_count, "checking register number");
 130   return &_register_block[register_number * 2];
 131 }
 132 
 133 
 134 
 135 int Deoptimization::UnrollBlock::size_of_frames() const {
 136   // Acount first for the adjustment of the initial frame
 137   int result = _caller_adjustment;
 138   for (int index = 0; index < number_of_frames(); index++) {
 139     result += frame_sizes()[index];
 140   }
 141   return result;
 142 }
 143 
 144 
 145 void Deoptimization::UnrollBlock::print() {
 146   ResourceMark rm;
 147   stringStream st;
 148   st.print_cr("UnrollBlock");
 149   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 150   st.print(   "  frame_sizes: ");
 151   for (int index = 0; index < number_of_frames(); index++) {
 152     st.print(INTX_FORMAT " ", frame_sizes()[index]);
 153   }
 154   st.cr();
 155   tty->print_raw(st.as_string());
 156 }
 157 
 158 
 159 // In order to make fetch_unroll_info work properly with escape
 160 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 161 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 162 // which is called from the method fetch_unroll_info_helper below.
 163 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 164   // fetch_unroll_info() is called at the beginning of the deoptimization
 165   // handler. Note this fact before we start generating temporary frames
 166   // that can confuse an asynchronous stack walker. This counter is
 167   // decremented at the end of unpack_frames().
 168   if (TraceDeoptimization) {
 169     tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(current));
 170   }
 171   current->inc_in_deopt_handler();
 172 
 173   if (exec_mode == Unpack_exception) {
 174     // When we get here, a callee has thrown an exception into a deoptimized
 175     // frame. That throw might have deferred stack watermark checking until
 176     // after unwinding. So we deal with such deferred requests here.
 177     StackWatermarkSet::after_unwind(current);
 178   }
 179 
 180   return fetch_unroll_info_helper(current, exec_mode);
 181 JRT_END
 182 
 183 #if COMPILER2_OR_JVMCI
 184 #ifndef PRODUCT
 185 // print information about reallocated objects
 186 static void print_objects(JavaThread* deoptee_thread,
 187                           GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
 188   ResourceMark rm;
 189   stringStream st;  // change to logStream with logging
 190   st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 191   fieldDescriptor fd;
 192 
 193   for (int i = 0; i < objects->length(); i++) {
 194     ObjectValue* sv = (ObjectValue*) objects->at(i);
 195     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
 196     Handle obj = sv->value();
 197 
 198     st.print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
 199     k->print_value_on(&st);
 200     assert(obj.not_null() || realloc_failures, "reallocation was missed");
 201     if (obj.is_null()) {
 202       st.print(" allocation failed");




 203     } else {
 204       st.print(" allocated (%d bytes)", obj->size() * HeapWordSize);
 205     }
 206     st.cr();
 207 
 208     if (Verbose && !obj.is_null()) {
 209       k->oop_print_on(obj(), &st);
 210     }
 211   }
 212   tty->print_raw(st.as_string());
 213 }
 214 #endif
 215 
 216 static bool rematerialize_objects(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,
 217                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 218                                   bool& deoptimized_objects) {
 219   bool realloc_failures = false;
 220   assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
 221 
 222   JavaThread* deoptee_thread = chunk->at(0)->thread();
 223   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
 224          "a frame can only be deoptimized by the owner thread");
 225 
 226   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
 227 
 228   // The flag return_oop() indicates call sites which return oop
 229   // in compiled code. Such sites include java method calls,
 230   // runtime calls (for example, used to allocate new objects/arrays
 231   // on slow code path) and any other calls generated in compiled code.
 232   // It is not guaranteed that we can get such information here only
 233   // by analyzing bytecode in deoptimized frames. This is why this flag
 234   // is set during method compilation (see Compile::Process_OopMap_Node()).
 235   // If the previous frame was popped or if we are dispatching an exception,
 236   // we don't have an oop result.
 237   bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 238   Handle return_value;











 239   if (save_oop_result) {
 240     // Reallocation may trigger GC. If deoptimization happened on return from
 241     // call which returns oop we need to save it since it is not in oopmap.
 242     oop result = deoptee.saved_oop_result(&map);
 243     assert(oopDesc::is_oop_or_null(result), "must be oop");
 244     return_value = Handle(thread, result);
 245     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 246     if (TraceDeoptimization) {
 247       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 248     }
 249   }
 250   if (objects != NULL) {
 251     if (exec_mode == Deoptimization::Unpack_none) {
 252       assert(thread->thread_state() == _thread_in_vm, "assumption");
 253       JavaThread* THREAD = thread; // For exception macros.
 254       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 255       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));







 256       deoptimized_objects = true;
 257     } else {
 258       JavaThread* current = thread; // For JRT_BLOCK
 259       JRT_BLOCK
 260       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);







 261       JRT_END
 262     }
 263     bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci();
 264     Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
 265 #ifndef PRODUCT
 266     if (TraceDeoptimization) {
 267       print_objects(deoptee_thread, objects, realloc_failures);
 268     }
 269 #endif
 270   }
 271   if (save_oop_result) {
 272     // Restore result.
 273     deoptee.set_saved_oop_result(&map, return_value());

 274   }
 275   return realloc_failures;
 276 }
 277 
 278 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 279                                      frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 280   JavaThread* deoptee_thread = chunk->at(0)->thread();
 281   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 282   assert(thread == Thread::current(), "should be");
 283   HandleMark hm(thread);
 284 #ifndef PRODUCT
 285   bool first = true;
 286 #endif
 287   for (int i = 0; i < chunk->length(); i++) {
 288     compiledVFrame* cvf = chunk->at(i);
 289     assert (cvf->scope() != NULL,"expect only compiled java frames");
 290     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 291     if (monitors->is_nonempty()) {
 292       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
 293                                                      exec_mode, realloc_failures);
 294       deoptimized_objects = deoptimized_objects || relocked;
 295 #ifndef PRODUCT
 296       if (PrintDeoptimizationDetails) {
 297         ResourceMark rm;
 298         stringStream st;
 299         for (int j = 0; j < monitors->length(); j++) {
 300           MonitorInfo* mi = monitors->at(j);
 301           if (mi->eliminated()) {
 302             if (first) {
 303               first = false;
 304               st.print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 305             }
 306             if (exec_mode == Deoptimization::Unpack_none) {
 307               ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
 308               if (monitor != NULL && monitor->object() == mi->owner()) {
 309                 st.print_cr("     object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
 310                 continue;
 311               }
 312             }
 313             if (mi->owner_is_scalar_replaced()) {
 314               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 315               st.print_cr("     failed reallocation for klass %s", k->external_name());
 316             } else {
 317               st.print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 318             }
 319           }
 320         }
 321         tty->print_raw(st.as_string());
 322       }
 323 #endif // !PRODUCT
 324     }
 325   }
 326 }
 327 
 328 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
 329 // The given vframes cover one physical frame.
 330 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,
 331                                                  bool& realloc_failures) {
 332   frame deoptee = chunk->at(0)->fr();
 333   JavaThread* deoptee_thread = chunk->at(0)->thread();
 334   CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
 335   RegisterMap map(chunk->at(0)->register_map());
 336   bool deoptimized_objects = false;
 337 
 338   bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false);
 339 
 340   // Reallocate the non-escaping objects and restore their fields.
 341   if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations)
 342                                       || EliminateAutoBox || EnableVectorAggressiveReboxing)) {
 343     realloc_failures = rematerialize_objects(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects);
 344   }
 345 
 346   // MonitorInfo structures used in eliminate_locks are not GC safe.
 347   NoSafepointVerifier no_safepoint;
 348 
 349   // Now relock objects if synchronization on them was eliminated.
 350   if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {
 351     restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
 352   }
 353   return deoptimized_objects;
 354 }
 355 #endif // COMPILER2_OR_JVMCI
 356 
 357 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 358 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {
 359   // When we get here we are about to unwind the deoptee frame. In order to
 360   // catch not yet safe to use frames, the following stack watermark barrier
 361   // poll will make such frames safe to use.
 362   StackWatermarkSet::before_unwind(current);
 363 
 364   // Note: there is a safepoint safety issue here. No matter whether we enter
 365   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
 366   // the vframeArray is created.
 367   //
 368 
 369   // Allocate our special deoptimization ResourceMark
 370   DeoptResourceMark* dmark = new DeoptResourceMark(current);
 371   assert(current->deopt_mark() == NULL, "Pending deopt!");
 372   current->set_deopt_mark(dmark);
 373 
 374   frame stub_frame = current->last_frame(); // Makes stack walkable as side effect
 375   RegisterMap map(current, true);
 376   RegisterMap dummy_map(current, false);
 377   // Now get the deoptee with a valid map
 378   frame deoptee = stub_frame.sender(&map);
 379   // Set the deoptee nmethod
 380   assert(current->deopt_compiled_method() == NULL, "Pending deopt!");
 381   CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
 382   current->set_deopt_compiled_method(cm);
 383 
 384   if (VerifyStack) {
 385     current->validate_frame_layout();
 386   }
 387 
 388   // Create a growable array of VFrames where each VFrame represents an inlined
 389   // Java frame.  This storage is allocated with the usual system arena.
 390   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 391   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 392   vframe* vf = vframe::new_vframe(&deoptee, &map, current);
 393   while (!vf->is_top()) {
 394     assert(vf->is_compiled_frame(), "Wrong frame type");
 395     chunk->push(compiledVFrame::cast(vf));
 396     vf = vf->sender();
 397   }
 398   assert(vf->is_compiled_frame(), "Wrong frame type");
 399   chunk->push(compiledVFrame::cast(vf));
 400 
 401   bool realloc_failures = false;
 402 
 403 #if COMPILER2_OR_JVMCI
 404   bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
 405 
 406   // Reallocate the non-escaping objects and restore their fields. Then
 407   // relock objects if synchronization on them was eliminated.
 408   if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations)
 409                                        || EliminateAutoBox || EnableVectorAggressiveReboxing )) {
 410     bool unused;
 411     realloc_failures = rematerialize_objects(current, exec_mode, cm, deoptee, map, chunk, unused);
 412   }
 413 #endif // COMPILER2_OR_JVMCI
 414 
 415   // Ensure that no safepoint is taken after pointers have been stored
 416   // in fields of rematerialized objects.  If a safepoint occurs from here on
 417   // out the java state residing in the vframeArray will be missed.
 418   // Locks may be rebaised in a safepoint.
 419   NoSafepointVerifier no_safepoint;
 420 
 421 #if COMPILER2_OR_JVMCI
 422   if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))
 423       && !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {
 424     bool unused;
 425     restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);
 426   }
 427 #endif // COMPILER2_OR_JVMCI
 428 
 429   ScopeDesc* trap_scope = chunk->at(0)->scope();
 430   Handle exceptionObject;
 431   if (trap_scope->rethrow_exception()) {
 432     if (PrintDeoptimizationDetails) {
 433       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());
 434     }
 435     GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
 436     guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");
 437     ScopeValue* topOfStack = expressions->top();
 438     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 439     guarantee(exceptionObject() != NULL, "exception oop can not be null");
 440   }
 441 
 442   vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);
 443 #if COMPILER2_OR_JVMCI
 444   if (realloc_failures) {
 445     pop_frames_failed_reallocs(current, array);
 446   }
 447 #endif
 448 
 449   assert(current->vframe_array_head() == NULL, "Pending deopt!");
 450   current->set_vframe_array_head(array);
 451 
 452   // Now that the vframeArray has been created if we have any deferred local writes
 453   // added by jvmti then we can free up that structure as the data is now in the
 454   // vframeArray
 455 
 456   JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());
 457 
 458   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 459   CodeBlob* cb = stub_frame.cb();
 460   // Verify we have the right vframeArray
 461   assert(cb->frame_size() >= 0, "Unexpected frame size");
 462   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 463 
 464   // If the deopt call site is a MethodHandle invoke call site we have
 465   // to adjust the unpack_sp.
 466   nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
 467   if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
 468     unpack_sp = deoptee.unextended_sp();
 469 
 470 #ifdef ASSERT
 471   assert(cb->is_deoptimization_stub() ||
 472          cb->is_uncommon_trap_stub() ||
 473          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 474          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 475          "unexpected code blob: %s", cb->name());
 476 #endif
 477 
 478   // This is a guarantee instead of an assert because if vframe doesn't match
 479   // we will unpack the wrong deoptimized frame and wind up in strange places
 480   // where it will be very difficult to figure out what went wrong. Better
 481   // to die an early death here than some very obscure death later when the
 482   // trail is cold.
 483   // Note: on ia64 this guarantee can be fooled by frames with no memory stack
 484   // in that it will fail to detect a problem when there is one. This needs
 485   // more work in tiger timeframe.
 486   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 487 
 488   int number_of_frames = array->frames();
 489 
 490   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 491   // virtual activation, which is the reverse of the elements in the vframes array.
 492   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 493   // +1 because we always have an interpreter return address for the final slot.
 494   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 495   int popframe_extra_args = 0;
 496   // Create an interpreter return address for the stub to use as its return
 497   // address so the skeletal frames are perfectly walkable
 498   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 499 
 500   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 501   // activation be put back on the expression stack of the caller for reexecution
 502   if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {
 503     popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());
 504   }
 505 
 506   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 507   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 508   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 509   //
 510   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 511   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 512 
 513   // It's possible that the number of parameters at the call site is
 514   // different than number of arguments in the callee when method
 515   // handles are used.  If the caller is interpreted get the real
 516   // value so that the proper amount of space can be added to it's
 517   // frame.
 518   bool caller_was_method_handle = false;
 519   if (deopt_sender.is_interpreted_frame()) {
 520     methodHandle method(current, deopt_sender.interpreter_frame_method());
 521     Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
 522     if (cur.is_invokedynamic() || cur.is_invokehandle()) {
 523       // Method handle invokes may involve fairly arbitrary chains of
 524       // calls so it's impossible to know how much actual space the
 525       // caller has for locals.
 526       caller_was_method_handle = true;
 527     }
 528   }
 529 
 530   //
 531   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 532   // frame_sizes/frame_pcs[1] next oldest frame (int)
 533   // frame_sizes/frame_pcs[n] youngest frame (int)
 534   //
 535   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 536   // owns the space for the return address to it's caller).  Confusing ain't it.
 537   //
 538   // The vframe array can address vframes with indices running from
 539   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 540   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 541   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 542   // so things look a little strange in this loop.
 543   //
 544   int callee_parameters = 0;
 545   int callee_locals = 0;
 546   for (int index = 0; index < array->frames(); index++ ) {
 547     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 548     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 549     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 550     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 551                                                                                                     callee_locals,
 552                                                                                                     index == 0,
 553                                                                                                     popframe_extra_args);
 554     // This pc doesn't have to be perfect just good enough to identify the frame
 555     // as interpreted so the skeleton frame will be walkable
 556     // The correct pc will be set when the skeleton frame is completely filled out
 557     // The final pc we store in the loop is wrong and will be overwritten below
 558     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 559 
 560     callee_parameters = array->element(index)->method()->size_of_parameters();
 561     callee_locals = array->element(index)->method()->max_locals();
 562     popframe_extra_args = 0;
 563   }
 564 
 565   // Compute whether the root vframe returns a float or double value.
 566   BasicType return_type;
 567   {
 568     methodHandle method(current, array->element(0)->method());
 569     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 570     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 571   }
 572 
 573   // Compute information for handling adapters and adjusting the frame size of the caller.
 574   int caller_adjustment = 0;
 575 
 576   // Compute the amount the oldest interpreter frame will have to adjust
 577   // its caller's stack by. If the caller is a compiled frame then
 578   // we pretend that the callee has no parameters so that the
 579   // extension counts for the full amount of locals and not just
 580   // locals-parms. This is because without a c2i adapter the parm
 581   // area as created by the compiled frame will not be usable by
 582   // the interpreter. (Depending on the calling convention there
 583   // may not even be enough space).
 584 
 585   // QQQ I'd rather see this pushed down into last_frame_adjust
 586   // and have it take the sender (aka caller).
 587 
 588   if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
 589     caller_adjustment = last_frame_adjust(0, callee_locals);
 590   } else if (callee_locals > callee_parameters) {
 591     // The caller frame may need extending to accommodate
 592     // non-parameter locals of the first unpacked interpreted frame.
 593     // Compute that adjustment.
 594     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 595   }
 596 
 597   // If the sender is deoptimized the we must retrieve the address of the handler
 598   // since the frame will "magically" show the original pc before the deopt
 599   // and we'd undo the deopt.
 600 
 601   frame_pcs[0] = deopt_sender.raw_pc();
 602 
 603   assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
 604 
 605 #if INCLUDE_JVMCI
 606   if (exceptionObject() != NULL) {
 607     current->set_exception_oop(exceptionObject());
 608     exec_mode = Unpack_exception;
 609   }
 610 #endif
 611 
 612   if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 613     assert(current->has_pending_exception(), "should have thrown OOME");
 614     current->set_exception_oop(current->pending_exception());
 615     current->clear_pending_exception();
 616     exec_mode = Unpack_exception;
 617   }
 618 
 619 #if INCLUDE_JVMCI
 620   if (current->frames_to_pop_failed_realloc() > 0) {
 621     current->set_pending_monitorenter(false);
 622   }
 623 #endif
 624 
 625   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 626                                       caller_adjustment * BytesPerWord,
 627                                       caller_was_method_handle ? 0 : callee_parameters,
 628                                       number_of_frames,
 629                                       frame_sizes,
 630                                       frame_pcs,
 631                                       return_type,
 632                                       exec_mode);
 633   // On some platforms, we need a way to pass some platform dependent
 634   // information to the unpacking code so the skeletal frames come out
 635   // correct (initial fp value, unextended sp, ...)
 636   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 637 
 638   if (array->frames() > 1) {
 639     if (VerifyStack && TraceDeoptimization) {
 640       tty->print_cr("Deoptimizing method containing inlining");
 641     }
 642   }
 643 
 644   array->set_unroll_block(info);
 645   return info;
 646 }
 647 
 648 // Called to cleanup deoptimization data structures in normal case
 649 // after unpacking to stack and when stack overflow error occurs
 650 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 651                                         vframeArray *array) {
 652 
 653   // Get array if coming from exception
 654   if (array == NULL) {
 655     array = thread->vframe_array_head();
 656   }
 657   thread->set_vframe_array_head(NULL);
 658 
 659   // Free the previous UnrollBlock
 660   vframeArray* old_array = thread->vframe_array_last();
 661   thread->set_vframe_array_last(array);
 662 
 663   if (old_array != NULL) {
 664     UnrollBlock* old_info = old_array->unroll_block();
 665     old_array->set_unroll_block(NULL);
 666     delete old_info;
 667     delete old_array;
 668   }
 669 
 670   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 671   // inside the vframeArray (StackValueCollections)
 672 
 673   delete thread->deopt_mark();
 674   thread->set_deopt_mark(NULL);
 675   thread->set_deopt_compiled_method(NULL);
 676 
 677 
 678   if (JvmtiExport::can_pop_frame()) {
 679     // Regardless of whether we entered this routine with the pending
 680     // popframe condition bit set, we should always clear it now
 681     thread->clear_popframe_condition();
 682   }
 683 
 684   // unpack_frames() is called at the end of the deoptimization handler
 685   // and (in C2) at the end of the uncommon trap handler. Note this fact
 686   // so that an asynchronous stack walker can work again. This counter is
 687   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 688   // the beginning of uncommon_trap().
 689   thread->dec_in_deopt_handler();
 690 }
 691 
 692 // Moved from cpu directories because none of the cpus has callee save values.
 693 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 694 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 695 
 696   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 697   // the days we had adapter frames. When we deoptimize a situation where a
 698   // compiled caller calls a compiled caller will have registers it expects
 699   // to survive the call to the callee. If we deoptimize the callee the only
 700   // way we can restore these registers is to have the oldest interpreter
 701   // frame that we create restore these values. That is what this routine
 702   // will accomplish.
 703 
 704   // At the moment we have modified c2 to not have any callee save registers
 705   // so this problem does not exist and this routine is just a place holder.
 706 
 707   assert(f->is_interpreted_frame(), "must be interpreted");
 708 }
 709 
 710 // Return BasicType of value being returned
 711 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 712 
 713   // We are already active in the special DeoptResourceMark any ResourceObj's we
 714   // allocate will be freed at the end of the routine.
 715 
 716   // JRT_LEAF methods don't normally allocate handles and there is a
 717   // NoHandleMark to enforce that. It is actually safe to use Handles
 718   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 719   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 720   // then use a HandleMark to ensure any Handles we do create are
 721   // cleaned up in this scope.
 722   ResetNoHandleMark rnhm;
 723   HandleMark hm(thread);
 724 
 725   frame stub_frame = thread->last_frame();
 726 
 727   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 728   // must point to the vframeArray for the unpack frame.
 729   vframeArray* array = thread->vframe_array_head();
 730 
 731 #ifndef PRODUCT
 732   if (TraceDeoptimization) {
 733     tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",
 734                   p2i(thread), p2i(array), exec_mode);
 735   }
 736 #endif
 737   Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
 738               p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);
 739 
 740   UnrollBlock* info = array->unroll_block();
 741 
 742   // We set the last_Java frame. But the stack isn't really parsable here. So we
 743   // clear it to make sure JFR understands not to try and walk stacks from events
 744   // in here.
 745   intptr_t* sp = thread->frame_anchor()->last_Java_sp();
 746   thread->frame_anchor()->set_last_Java_sp(NULL);
 747 
 748   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 749   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 750 
 751   thread->frame_anchor()->set_last_Java_sp(sp);
 752 
 753   BasicType bt = info->return_type();
 754 
 755   // If we have an exception pending, claim that the return type is an oop
 756   // so the deopt_blob does not overwrite the exception_oop.
 757 
 758   if (exec_mode == Unpack_exception)
 759     bt = T_OBJECT;
 760 
 761   // Cleanup thread deopt data
 762   cleanup_deopt_info(thread, array);
 763 
 764 #ifndef PRODUCT
 765   if (VerifyStack) {
 766     ResourceMark res_mark;
 767     // Clear pending exception to not break verification code (restored afterwards)
 768     PreserveExceptionMark pm(thread);
 769 
 770     thread->validate_frame_layout();
 771 
 772     // Verify that the just-unpacked frames match the interpreter's
 773     // notions of expression stack and locals
 774     vframeArray* cur_array = thread->vframe_array_last();
 775     RegisterMap rm(thread, false);
 776     rm.set_include_argument_oops(false);
 777     bool is_top_frame = true;
 778     int callee_size_of_parameters = 0;
 779     int callee_max_locals = 0;
 780     for (int i = 0; i < cur_array->frames(); i++) {
 781       vframeArrayElement* el = cur_array->element(i);
 782       frame* iframe = el->iframe();
 783       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 784 
 785       // Get the oop map for this bci
 786       InterpreterOopMap mask;
 787       int cur_invoke_parameter_size = 0;
 788       bool try_next_mask = false;
 789       int next_mask_expression_stack_size = -1;
 790       int top_frame_expression_stack_adjustment = 0;
 791       methodHandle mh(thread, iframe->interpreter_frame_method());
 792       OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
 793       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 794       int max_bci = mh->code_size();
 795       // Get to the next bytecode if possible
 796       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 797       // Check to see if we can grab the number of outgoing arguments
 798       // at an uncommon trap for an invoke (where the compiler
 799       // generates debug info before the invoke has executed)
 800       Bytecodes::Code cur_code = str.next();
 801       if (Bytecodes::is_invoke(cur_code)) {
 802         Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
 803         cur_invoke_parameter_size = invoke.size_of_parameters();
 804         if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
 805           callee_size_of_parameters++;
 806         }
 807       }
 808       if (str.bci() < max_bci) {
 809         Bytecodes::Code next_code = str.next();
 810         if (next_code >= 0) {
 811           // The interpreter oop map generator reports results before
 812           // the current bytecode has executed except in the case of
 813           // calls. It seems to be hard to tell whether the compiler
 814           // has emitted debug information matching the "state before"
 815           // a given bytecode or the state after, so we try both
 816           if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) {
 817             // Get expression stack size for the next bytecode
 818             InterpreterOopMap next_mask;
 819             OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
 820             next_mask_expression_stack_size = next_mask.expression_stack_size();
 821             if (Bytecodes::is_invoke(next_code)) {
 822               Bytecode_invoke invoke(mh, str.bci());
 823               next_mask_expression_stack_size += invoke.size_of_parameters();
 824             }
 825             // Need to subtract off the size of the result type of
 826             // the bytecode because this is not described in the
 827             // debug info but returned to the interpreter in the TOS
 828             // caching register
 829             BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
 830             if (bytecode_result_type != T_ILLEGAL) {
 831               top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
 832             }
 833             assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
 834             try_next_mask = true;
 835           }
 836         }
 837       }
 838 
 839       // Verify stack depth and oops in frame
 840       // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
 841       if (!(
 842             /* SPARC */
 843             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
 844             /* x86 */
 845             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
 846             (try_next_mask &&
 847              (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
 848                                                                     top_frame_expression_stack_adjustment))) ||
 849             (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
 850             (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
 851              (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
 852             )) {
 853         {
 854           // Print out some information that will help us debug the problem
 855           tty->print_cr("Wrong number of expression stack elements during deoptimization");
 856           tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
 857           tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
 858                         iframe->interpreter_frame_expression_stack_size());
 859           tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
 860           tty->print_cr("  try_next_mask = %d", try_next_mask);
 861           tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
 862           tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
 863           tty->print_cr("  callee_max_locals = %d", callee_max_locals);
 864           tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
 865           tty->print_cr("  exec_mode = %d", exec_mode);
 866           tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
 867           tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
 868           tty->print_cr("  Interpreted frames:");
 869           for (int k = 0; k < cur_array->frames(); k++) {
 870             vframeArrayElement* el = cur_array->element(k);
 871             tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
 872           }
 873           cur_array->print_on_2(tty);
 874         }
 875         guarantee(false, "wrong number of expression stack elements during deopt");
 876       }
 877       VerifyOopClosure verify;
 878       iframe->oops_interpreted_do(&verify, &rm, false);
 879       callee_size_of_parameters = mh->size_of_parameters();
 880       callee_max_locals = mh->max_locals();
 881       is_top_frame = false;
 882     }
 883   }
 884 #endif /* !PRODUCT */
 885 
 886   return bt;
 887 JRT_END
 888 
 889 class DeoptimizeMarkedClosure : public HandshakeClosure {
 890  public:
 891   DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}
 892   void do_thread(Thread* thread) {
 893     JavaThread* jt = JavaThread::cast(thread);
 894     jt->deoptimize_marked_methods();
 895   }
 896 };
 897 
 898 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) {
 899   ResourceMark rm;
 900   DeoptimizationMarker dm;
 901 
 902   // Make the dependent methods not entrant
 903   if (nmethod_only != NULL) {
 904     nmethod_only->mark_for_deoptimization();
 905     nmethod_only->make_not_entrant();
 906   } else {
 907     MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag);
 908     CodeCache::make_marked_nmethods_not_entrant();
 909   }
 910 
 911   DeoptimizeMarkedClosure deopt;
 912   if (SafepointSynchronize::is_at_safepoint()) {
 913     Threads::java_threads_do(&deopt);
 914   } else {
 915     Handshake::execute(&deopt);
 916   }
 917 }
 918 
 919 Deoptimization::DeoptAction Deoptimization::_unloaded_action
 920   = Deoptimization::Action_reinterpret;
 921 
 922 #if COMPILER2_OR_JVMCI
 923 template<typename CacheType>
 924 class BoxCacheBase : public CHeapObj<mtCompiler> {
 925 protected:
 926   static InstanceKlass* find_cache_klass(Symbol* klass_name) {
 927     ResourceMark rm;
 928     char* klass_name_str = klass_name->as_C_string();
 929     InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle());
 930     guarantee(ik != NULL, "%s must be loaded", klass_name_str);
 931     guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
 932     CacheType::compute_offsets(ik);
 933     return ik;
 934   }
 935 };
 936 
 937 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache  : public BoxCacheBase<CacheType> {
 938   PrimitiveType _low;
 939   PrimitiveType _high;
 940   jobject _cache;
 941 protected:
 942   static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
 943   BoxCache(Thread* thread) {
 944     InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol());
 945     objArrayOop cache = CacheType::cache(ik);
 946     assert(cache->length() > 0, "Empty cache");
 947     _low = BoxType::value(cache->obj_at(0));
 948     _high = _low + cache->length() - 1;
 949     _cache = JNIHandles::make_global(Handle(thread, cache));
 950   }
 951   ~BoxCache() {
 952     JNIHandles::destroy_global(_cache);
 953   }
 954 public:
 955   static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
 956     if (_singleton == NULL) {
 957       BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
 958       if (!Atomic::replace_if_null(&_singleton, s)) {
 959         delete s;
 960       }
 961     }
 962     return _singleton;
 963   }
 964   oop lookup(PrimitiveType value) {
 965     if (_low <= value && value <= _high) {
 966       int offset = value - _low;
 967       return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
 968     }
 969     return NULL;
 970   }
 971   oop lookup_raw(intptr_t raw_value) {
 972     // Have to cast to avoid little/big-endian problems.
 973     if (sizeof(PrimitiveType) > sizeof(jint)) {
 974       jlong value = (jlong)raw_value;
 975       return lookup(value);
 976     }
 977     PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
 978     return lookup(value);
 979   }
 980 };
 981 
 982 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
 983 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
 984 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
 985 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
 986 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
 987 
 988 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL;
 989 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL;
 990 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL;
 991 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL;
 992 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL;
 993 
 994 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
 995   jobject _true_cache;
 996   jobject _false_cache;
 997 protected:
 998   static BooleanBoxCache *_singleton;
 999   BooleanBoxCache(Thread *thread) {
1000     InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol());
1001     _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
1002     _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
1003   }
1004   ~BooleanBoxCache() {
1005     JNIHandles::destroy_global(_true_cache);
1006     JNIHandles::destroy_global(_false_cache);
1007   }
1008 public:
1009   static BooleanBoxCache* singleton(Thread* thread) {
1010     if (_singleton == NULL) {
1011       BooleanBoxCache* s = new BooleanBoxCache(thread);
1012       if (!Atomic::replace_if_null(&_singleton, s)) {
1013         delete s;
1014       }
1015     }
1016     return _singleton;
1017   }
1018   oop lookup_raw(intptr_t raw_value) {
1019     // Have to cast to avoid little/big-endian problems.
1020     jboolean value = (jboolean)*((jint*)&raw_value);
1021     return lookup(value);
1022   }
1023   oop lookup(jboolean value) {
1024     if (value != 0) {
1025       return JNIHandles::resolve_non_null(_true_cache);
1026     }
1027     return JNIHandles::resolve_non_null(_false_cache);
1028   }
1029 };
1030 
1031 BooleanBoxCache* BooleanBoxCache::_singleton = NULL;
1032 
1033 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) {
1034    Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
1035    BasicType box_type = vmClasses::box_klass_type(k);
1036    if (box_type != T_OBJECT) {
1037      StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
1038      switch(box_type) {
1039        case T_INT:     return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1040        case T_CHAR:    return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1041        case T_SHORT:   return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1042        case T_BYTE:    return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1043        case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1044        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
1045        default:;
1046      }
1047    }
1048    return NULL;
1049 }
1050 
1051 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1052   Handle pending_exception(THREAD, thread->pending_exception());
1053   const char* exception_file = thread->exception_file();
1054   int exception_line = thread->exception_line();
1055   thread->clear_pending_exception();
1056 
1057   bool failures = false;
1058 
1059   for (int i = 0; i < objects->length(); i++) {
1060     assert(objects->at(i)->is_object(), "invalid debug information");
1061     ObjectValue* sv = (ObjectValue*) objects->at(i);
1062 
1063     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1064     oop obj = NULL;
1065 












1066     if (k->is_instance_klass()) {
1067       if (sv->is_auto_box()) {
1068         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1069         obj = get_cached_box(abv, fr, reg_map, THREAD);
1070         if (obj != NULL) {
1071           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1072           abv->set_cached(true);
1073         }
1074       }
1075 
1076       InstanceKlass* ik = InstanceKlass::cast(k);
1077       if (obj == NULL) {
1078 #ifdef COMPILER2
1079         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1080           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1081         } else {
1082           obj = ik->allocate_instance(THREAD);
1083         }
1084 #else
1085         obj = ik->allocate_instance(THREAD);
1086 #endif // COMPILER2
1087       }




1088     } else if (k->is_typeArray_klass()) {
1089       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1090       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1091       int len = sv->field_size() / type2size[ak->element_type()];
1092       obj = ak->allocate(len, THREAD);
1093     } else if (k->is_objArray_klass()) {
1094       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1095       obj = ak->allocate(sv->field_size(), THREAD);
1096     }
1097 
1098     if (obj == NULL) {
1099       failures = true;
1100     }
1101 
1102     assert(sv->value().is_null(), "redundant reallocation");
1103     assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
1104     CLEAR_PENDING_EXCEPTION;
1105     sv->set_value(obj);
1106   }
1107 
1108   if (failures) {
1109     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1110   } else if (pending_exception.not_null()) {
1111     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1112   }
1113 
1114   return failures;
1115 }
1116 















1117 #if INCLUDE_JVMCI
1118 /**
1119  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1120  * we need to somehow be able to recover the actual kind to be able to write the correct
1121  * amount of bytes.
1122  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1123  * the entries at index n + 1 to n + i are 'markers'.
1124  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1125  * expected form of the array would be:
1126  *
1127  * {b0, b1, b2, b3, INT, marker, b6, b7}
1128  *
1129  * Thus, in order to get back the size of the entry, we simply need to count the number
1130  * of marked entries
1131  *
1132  * @param virtualArray the virtualized byte array
1133  * @param i index of the virtual entry we are recovering
1134  * @return The number of bytes the entry spans
1135  */
1136 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1137   int index = i;
1138   while (++index < virtualArray->field_size() &&
1139            virtualArray->field_at(index)->is_marker()) {}
1140   return index - i;
1141 }
1142 
1143 /**
1144  * If there was a guarantee for byte array to always start aligned to a long, we could
1145  * do a simple check on the parity of the index. Unfortunately, that is not always the
1146  * case. Thus, we check alignment of the actual address we are writing to.
1147  * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1148  * write a long to index 3.
1149  */
1150 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1151     jbyte* res = obj->byte_at_addr(index);
1152     assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1153     return res;
1154 }
1155 
1156 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {
1157   switch (byte_count) {
1158     case 1:
1159       obj->byte_at_put(index, (jbyte) *((jint *) &val));
1160       break;
1161     case 2:
1162       *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);
1163       break;
1164     case 4:
1165       *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);
1166       break;
1167     case 8:
1168       *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val);
1169       break;
1170     default:
1171       ShouldNotReachHere();
1172   }
1173 }
1174 #endif // INCLUDE_JVMCI
1175 
1176 
1177 // restore elements of an eliminated type array
1178 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1179   int index = 0;
1180   intptr_t val;
1181 
1182   for (int i = 0; i < sv->field_size(); i++) {
1183     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1184     switch(type) {
1185     case T_LONG: case T_DOUBLE: {
1186       assert(value->type() == T_INT, "Agreement.");
1187       StackValue* low =
1188         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1189 #ifdef _LP64
1190       jlong res = (jlong)low->get_int();
1191 #else
1192       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1193 #endif
1194       obj->long_at_put(index, res);
1195       break;
1196     }
1197 
1198     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1199     case T_INT: case T_FLOAT: { // 4 bytes.
1200       assert(value->type() == T_INT, "Agreement.");
1201       bool big_value = false;
1202       if (i + 1 < sv->field_size() && type == T_INT) {
1203         if (sv->field_at(i)->is_location()) {
1204           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1205           if (type == Location::dbl || type == Location::lng) {
1206             big_value = true;
1207           }
1208         } else if (sv->field_at(i)->is_constant_int()) {
1209           ScopeValue* next_scope_field = sv->field_at(i + 1);
1210           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1211             big_value = true;
1212           }
1213         }
1214       }
1215 
1216       if (big_value) {
1217         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1218   #ifdef _LP64
1219         jlong res = (jlong)low->get_int();
1220   #else
1221         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1222   #endif
1223         obj->int_at_put(index, (jint)*((jint*)&res));
1224         obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
1225       } else {
1226         val = value->get_int();
1227         obj->int_at_put(index, (jint)*((jint*)&val));
1228       }
1229       break;
1230     }
1231 
1232     case T_SHORT:
1233       assert(value->type() == T_INT, "Agreement.");
1234       val = value->get_int();
1235       obj->short_at_put(index, (jshort)*((jint*)&val));
1236       break;
1237 
1238     case T_CHAR:
1239       assert(value->type() == T_INT, "Agreement.");
1240       val = value->get_int();
1241       obj->char_at_put(index, (jchar)*((jint*)&val));
1242       break;
1243 
1244     case T_BYTE: {
1245       assert(value->type() == T_INT, "Agreement.");
1246       // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1247       val = value->get_int();
1248 #if INCLUDE_JVMCI
1249       int byte_count = count_number_of_bytes_for_entry(sv, i);
1250       byte_array_put(obj, val, index, byte_count);
1251       // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1252       i += byte_count - 1; // Balance the loop counter.
1253       index += byte_count;
1254       // index has been updated so continue at top of loop
1255       continue;
1256 #else
1257       obj->byte_at_put(index, (jbyte)*((jint*)&val));
1258       break;
1259 #endif // INCLUDE_JVMCI
1260     }
1261 
1262     case T_BOOLEAN: {
1263       assert(value->type() == T_INT, "Agreement.");
1264       val = value->get_int();
1265       obj->bool_at_put(index, (jboolean)*((jint*)&val));
1266       break;
1267     }
1268 
1269       default:
1270         ShouldNotReachHere();
1271     }
1272     index++;
1273   }
1274 }
1275 
1276 // restore fields of an eliminated object array
1277 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1278   for (int i = 0; i < sv->field_size(); i++) {
1279     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1280     assert(value->type() == T_OBJECT, "object element expected");
1281     obj->obj_at_put(i, value->get_obj()());
1282   }
1283 }
1284 
1285 class ReassignedField {
1286 public:
1287   int _offset;
1288   BasicType _type;

1289 public:
1290   ReassignedField() {
1291     _offset = 0;
1292     _type = T_ILLEGAL;

1293   }
1294 };
1295 
1296 int compare(ReassignedField* left, ReassignedField* right) {
1297   return left->_offset - right->_offset;
1298 }
1299 
1300 // Restore fields of an eliminated instance object using the same field order
1301 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
1302 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
1303   GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
1304   InstanceKlass* ik = klass;
1305   while (ik != NULL) {
1306     for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1307       if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
1308         ReassignedField field;
1309         field._offset = fs.offset();
1310         field._type = Signature::basic_type(fs.signature());








1311         fields->append(field);
1312       }
1313     }
1314     ik = ik->superklass();
1315   }
1316   fields->sort(compare);
1317   for (int i = 0; i < fields->length(); i++) {











1318     intptr_t val;
1319     ScopeValue* scope_field = sv->field_at(svIndex);
1320     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1321     int offset = fields->at(i)._offset;
1322     BasicType type = fields->at(i)._type;
1323     switch (type) {
1324       case T_OBJECT: case T_ARRAY:

1325         assert(value->type() == T_OBJECT, "Agreement.");
1326         obj->obj_field_put(offset, value->get_obj()());
1327         break;
1328 
1329       // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1330       case T_INT: case T_FLOAT: { // 4 bytes.
1331         assert(value->type() == T_INT, "Agreement.");
1332         bool big_value = false;
1333         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1334           if (scope_field->is_location()) {
1335             Location::Type type = ((LocationValue*) scope_field)->location().type();
1336             if (type == Location::dbl || type == Location::lng) {
1337               big_value = true;
1338             }
1339           }
1340           if (scope_field->is_constant_int()) {
1341             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1342             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1343               big_value = true;
1344             }
1345           }
1346         }
1347 
1348         if (big_value) {
1349           i++;
1350           assert(i < fields->length(), "second T_INT field needed");
1351           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1352         } else {
1353           val = value->get_int();
1354           obj->int_field_put(offset, (jint)*((jint*)&val));
1355           break;
1356         }
1357       }
1358         /* no break */
1359 
1360       case T_LONG: case T_DOUBLE: {
1361         assert(value->type() == T_INT, "Agreement.");
1362         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1363 #ifdef _LP64
1364         jlong res = (jlong)low->get_int();
1365 #else
1366         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1367 #endif
1368         obj->long_field_put(offset, res);
1369         break;
1370       }
1371 
1372       case T_SHORT:
1373         assert(value->type() == T_INT, "Agreement.");
1374         val = value->get_int();
1375         obj->short_field_put(offset, (jshort)*((jint*)&val));
1376         break;
1377 
1378       case T_CHAR:
1379         assert(value->type() == T_INT, "Agreement.");
1380         val = value->get_int();
1381         obj->char_field_put(offset, (jchar)*((jint*)&val));
1382         break;
1383 
1384       case T_BYTE:
1385         assert(value->type() == T_INT, "Agreement.");
1386         val = value->get_int();
1387         obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1388         break;
1389 
1390       case T_BOOLEAN:
1391         assert(value->type() == T_INT, "Agreement.");
1392         val = value->get_int();
1393         obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1394         break;
1395 
1396       default:
1397         ShouldNotReachHere();
1398     }
1399     svIndex++;
1400   }
1401   return svIndex;
1402 }
1403 














1404 // restore fields of all eliminated objects and arrays
1405 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
1406   for (int i = 0; i < objects->length(); i++) {
1407     ObjectValue* sv = (ObjectValue*) objects->at(i);
1408     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1409     Handle obj = sv->value();
1410     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1411     if (PrintDeoptimizationDetails) {
1412       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1413     }
1414     if (obj.is_null()) {
1415       continue;
1416     }
1417 
1418     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1419     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1420       continue;
1421     }
1422 #ifdef COMPILER2
1423     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1424       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1425       ScopeValue* payload = sv->field_at(0);
1426       if (payload->is_location() &&
1427           payload->as_LocationValue()->location().type() == Location::vector) {
1428         if (PrintDeoptimizationDetails) {
1429           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1430           if (Verbose) {
1431             Handle obj = sv->value();
1432             k->oop_print_on(obj(), tty);
1433           }
1434         }
1435         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1436       }
1437       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1438       // which could be restored after vector object allocation.
1439     }
1440 #endif
1441     if (k->is_instance_klass()) {
1442       InstanceKlass* ik = InstanceKlass::cast(k);
1443       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);



1444     } else if (k->is_typeArray_klass()) {
1445       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1446       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1447     } else if (k->is_objArray_klass()) {
1448       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1449     }
1450   }
1451 }
1452 
1453 
1454 // relock objects for which synchronization was eliminated
1455 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1456                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1457   bool relocked_objects = false;
1458   for (int i = 0; i < monitors->length(); i++) {
1459     MonitorInfo* mon_info = monitors->at(i);
1460     if (mon_info->eliminated()) {
1461       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1462       relocked_objects = true;
1463       if (!mon_info->owner_is_scalar_replaced()) {
1464         Handle obj(thread, mon_info->owner());
1465         markWord mark = obj->mark();
1466         if (exec_mode == Unpack_none) {
1467           if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {
1468             // With exec_mode == Unpack_none obj may be thread local and locked in
1469             // a callee frame. Make the lock in the callee a recursive lock and restore the displaced header.
1470             markWord dmw = mark.displaced_mark_helper();
1471             mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL));
1472             obj->set_mark(dmw);
1473           }
1474           if (mark.has_monitor()) {
1475             // defer relocking if the deoptee thread is currently waiting for obj
1476             ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1477             if (waiting_monitor != NULL && waiting_monitor->object() == obj()) {
1478               assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1479               mon_info->lock()->set_displaced_header(markWord::unused_mark());
1480               JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1481               continue;
1482             }
1483           }
1484         }
1485         BasicLock* lock = mon_info->lock();
1486         ObjectSynchronizer::enter(obj, lock, deoptee_thread);
1487         assert(mon_info->owner()->is_locked(), "object must be locked now");
1488       }
1489     }
1490   }
1491   return relocked_objects;
1492 }
1493 #endif // COMPILER2_OR_JVMCI
1494 
1495 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1496   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1497 
1498 #ifndef PRODUCT
1499   if (PrintDeoptimizationDetails) {
1500     ResourceMark rm;
1501     stringStream st;
1502     st.print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));
1503     fr.print_on(&st);
1504     st.print_cr("     Virtual frames (innermost first):");
1505     for (int index = 0; index < chunk->length(); index++) {
1506       compiledVFrame* vf = chunk->at(index);
1507       st.print("       %2d - ", index);
1508       vf->print_value_on(&st);
1509       int bci = chunk->at(index)->raw_bci();
1510       const char* code_name;
1511       if (bci == SynchronizationEntryBCI) {
1512         code_name = "sync entry";
1513       } else {
1514         Bytecodes::Code code = vf->method()->code_at(bci);
1515         code_name = Bytecodes::name(code);
1516       }
1517       st.print(" - %s", code_name);
1518       st.print_cr(" @ bci %d ", bci);
1519       if (Verbose) {
1520         vf->print_on(&st);
1521         st.cr();
1522       }
1523     }
1524     tty->print_raw(st.as_string());
1525   }
1526 #endif
1527 
1528   // Register map for next frame (used for stack crawl).  We capture
1529   // the state of the deopt'ing frame's caller.  Thus if we need to
1530   // stuff a C2I adapter we can properly fill in the callee-save
1531   // register locations.
1532   frame caller = fr.sender(reg_map);
1533   int frame_size = caller.sp() - fr.sp();
1534 
1535   frame sender = caller;
1536 
1537   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1538   // the vframeArray containing the unpacking information is allocated in the C heap.
1539   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1540   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1541 
1542   // Compare the vframeArray to the collected vframes
1543   assert(array->structural_compare(thread, chunk), "just checking");
1544 
1545 #ifndef PRODUCT
1546   if (PrintDeoptimizationDetails) {
1547     tty->print_cr("     Created vframeArray " INTPTR_FORMAT, p2i(array));
1548   }
1549 #endif // PRODUCT
1550 
1551   return array;
1552 }
1553 
1554 #if COMPILER2_OR_JVMCI
1555 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1556   // Reallocation of some scalar replaced objects failed. Record
1557   // that we need to pop all the interpreter frames for the
1558   // deoptimized compiled frame.
1559   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1560   thread->set_frames_to_pop_failed_realloc(array->frames());
1561   // Unlock all monitors here otherwise the interpreter will see a
1562   // mix of locked and unlocked monitors (because of failed
1563   // reallocations of synchronized objects) and be confused.
1564   for (int i = 0; i < array->frames(); i++) {
1565     MonitorChunk* monitors = array->element(i)->monitors();
1566     if (monitors != NULL) {
1567       for (int j = 0; j < monitors->number_of_monitors(); j++) {
1568         BasicObjectLock* src = monitors->at(j);
1569         if (src->obj() != NULL) {
1570           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1571         }
1572       }
1573       array->element(i)->free_monitors(thread);
1574 #ifdef ASSERT
1575       array->element(i)->set_removed_monitors();
1576 #endif
1577     }
1578   }
1579 }
1580 #endif
1581 
1582 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1583   assert(fr.can_be_deoptimized(), "checking frame type");
1584 
1585   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1586 
1587   if (LogCompilation && xtty != NULL) {
1588     CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();
1589     assert(cm != NULL, "only compiled methods can deopt");
1590 
1591     ttyLocker ttyl;
1592     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1593     cm->log_identity(xtty);
1594     xtty->end_head();
1595     for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1596       xtty->begin_elem("jvms bci='%d'", sd->bci());
1597       xtty->method(sd->method());
1598       xtty->end_elem();
1599       if (sd->is_top())  break;
1600     }
1601     xtty->tail("deoptimized");
1602   }
1603 
1604   // Patch the compiled method so that when execution returns to it we will
1605   // deopt the execution state and return to the interpreter.
1606   fr.deoptimize(thread);
1607 }
1608 
1609 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1610   // Deoptimize only if the frame comes from compile code.
1611   // Do not deoptimize the frame which is already patched
1612   // during the execution of the loops below.
1613   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1614     return;
1615   }
1616   ResourceMark rm;
1617   DeoptimizationMarker dm;
1618   deoptimize_single_frame(thread, fr, reason);
1619 }
1620 
1621 #if INCLUDE_JVMCI
1622 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {
1623   // there is no exception handler for this pc => deoptimize
1624   cm->make_not_entrant();
1625 
1626   // Use Deoptimization::deoptimize for all of its side-effects:
1627   // gathering traps statistics, logging...
1628   // it also patches the return pc but we do not care about that
1629   // since we return a continuation to the deopt_blob below.
1630   JavaThread* thread = JavaThread::current();
1631   RegisterMap reg_map(thread, false);
1632   frame runtime_frame = thread->last_frame();
1633   frame caller_frame = runtime_frame.sender(&reg_map);
1634   assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");
1635   vframe* vf = vframe::new_vframe(&caller_frame, &reg_map, thread);
1636   compiledVFrame* cvf = compiledVFrame::cast(vf);
1637   ScopeDesc* imm_scope = cvf->scope();
1638   MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);
1639   if (imm_mdo != NULL) {
1640     ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), NULL);
1641     if (pdata != NULL && pdata->is_BitData()) {
1642       BitData* bit_data = (BitData*) pdata;
1643       bit_data->set_exception_seen();
1644     }
1645   }
1646 
1647   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1648 
1649   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);
1650   if (trap_mdo != NULL) {
1651     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1652   }
1653 
1654   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1655 }
1656 #endif
1657 
1658 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1659   assert(thread == Thread::current() ||
1660          thread->is_handshake_safe_for(Thread::current()) ||
1661          SafepointSynchronize::is_at_safepoint(),
1662          "can only deoptimize other thread at a safepoint/handshake");
1663   // Compute frame and register map based on thread and sp.
1664   RegisterMap reg_map(thread, false);
1665   frame fr = thread->last_frame();
1666   while (fr.id() != id) {
1667     fr = fr.sender(&reg_map);
1668   }
1669   deoptimize(thread, fr, reason);
1670 }
1671 
1672 
1673 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1674   Thread* current = Thread::current();
1675   if (thread == current || thread->is_handshake_safe_for(current)) {
1676     Deoptimization::deoptimize_frame_internal(thread, id, reason);
1677   } else {
1678     VM_DeoptimizeFrame deopt(thread, id, reason);
1679     VMThread::execute(&deopt);
1680   }
1681 }
1682 
1683 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1684   deoptimize_frame(thread, id, Reason_constraint);
1685 }
1686 
1687 // JVMTI PopFrame support
1688 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1689 {
1690   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1691 }
1692 JRT_END
1693 
1694 MethodData*
1695 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1696                                 bool create_if_missing) {
1697   JavaThread* THREAD = thread; // For exception macros.
1698   MethodData* mdo = m()->method_data();
1699   if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1700     // Build an MDO.  Ignore errors like OutOfMemory;
1701     // that simply means we won't have an MDO to update.
1702     Method::build_interpreter_method_data(m, THREAD);
1703     if (HAS_PENDING_EXCEPTION) {
1704       // Only metaspace OOM is expected. No Java code executed.
1705       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1706       CLEAR_PENDING_EXCEPTION;
1707     }
1708     mdo = m()->method_data();
1709   }
1710   return mdo;
1711 }
1712 
1713 #if COMPILER2_OR_JVMCI
1714 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1715   // In case of an unresolved klass entry, load the class.
1716   // This path is exercised from case _ldc in Parse::do_one_bytecode,
1717   // and probably nowhere else.
1718   // Even that case would benefit from simply re-interpreting the
1719   // bytecode, without paying special attention to the class index.
1720   // So this whole "class index" feature should probably be removed.
1721 
1722   if (constant_pool->tag_at(index).is_unresolved_klass()) {
1723     Klass* tk = constant_pool->klass_at(index, THREAD);
1724     if (HAS_PENDING_EXCEPTION) {
1725       // Exception happened during classloading. We ignore the exception here, since it
1726       // is going to be rethrown since the current activation is going to be deoptimized and
1727       // the interpreter will re-execute the bytecode.
1728       // Do not clear probable Async Exceptions.
1729       CLEAR_PENDING_NONASYNC_EXCEPTION;
1730       // Class loading called java code which may have caused a stack
1731       // overflow. If the exception was thrown right before the return
1732       // to the runtime the stack is no longer guarded. Reguard the
1733       // stack otherwise if we return to the uncommon trap blob and the
1734       // stack bang causes a stack overflow we crash.
1735       JavaThread* jt = THREAD;
1736       bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();
1737       assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1738     }
1739     return;
1740   }
1741 
1742   assert(!constant_pool->tag_at(index).is_symbol(),
1743          "no symbolic names here, please");
1744 }
1745 
1746 #if INCLUDE_JFR
1747 
1748 class DeoptReasonSerializer : public JfrSerializer {
1749  public:
1750   void serialize(JfrCheckpointWriter& writer) {
1751     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1752     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1753       writer.write_key((u8)i);
1754       writer.write(Deoptimization::trap_reason_name(i));
1755     }
1756   }
1757 };
1758 
1759 class DeoptActionSerializer : public JfrSerializer {
1760  public:
1761   void serialize(JfrCheckpointWriter& writer) {
1762     static const u4 nof_actions = Deoptimization::Action_LIMIT;
1763     writer.write_count(nof_actions);
1764     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1765       writer.write_key(i);
1766       writer.write(Deoptimization::trap_action_name((int)i));
1767     }
1768   }
1769 };
1770 
1771 static void register_serializers() {
1772   static int critical_section = 0;
1773   if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
1774     return;
1775   }
1776   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1777   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1778 }
1779 
1780 static void post_deoptimization_event(CompiledMethod* nm,
1781                                       const Method* method,
1782                                       int trap_bci,
1783                                       int instruction,
1784                                       Deoptimization::DeoptReason reason,
1785                                       Deoptimization::DeoptAction action) {
1786   assert(nm != NULL, "invariant");
1787   assert(method != NULL, "invariant");
1788   if (EventDeoptimization::is_enabled()) {
1789     static bool serializers_registered = false;
1790     if (!serializers_registered) {
1791       register_serializers();
1792       serializers_registered = true;
1793     }
1794     EventDeoptimization event;
1795     event.set_compileId(nm->compile_id());
1796     event.set_compiler(nm->compiler_type());
1797     event.set_method(method);
1798     event.set_lineNumber(method->line_number_from_bci(trap_bci));
1799     event.set_bci(trap_bci);
1800     event.set_instruction(instruction);
1801     event.set_reason(reason);
1802     event.set_action(action);
1803     event.commit();
1804   }
1805 }
1806 
1807 #endif // INCLUDE_JFR
1808 
1809 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
1810   HandleMark hm(current);
1811 
1812   // uncommon_trap() is called at the beginning of the uncommon trap
1813   // handler. Note this fact before we start generating temporary frames
1814   // that can confuse an asynchronous stack walker. This counter is
1815   // decremented at the end of unpack_frames().
1816   current->inc_in_deopt_handler();
1817 
1818 #if INCLUDE_JVMCI
1819   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
1820   RegisterMap reg_map(current, true);
1821 #else
1822   RegisterMap reg_map(current, false);
1823 #endif
1824   frame stub_frame = current->last_frame();
1825   frame fr = stub_frame.sender(&reg_map);
1826   // Make sure the calling nmethod is not getting deoptimized and removed
1827   // before we are done with it.
1828   nmethodLocker nl(fr.pc());
1829 
1830   // Log a message
1831   Events::log_deopt_message(current, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
1832               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
1833 
1834   {
1835     ResourceMark rm;
1836 
1837     DeoptReason reason = trap_request_reason(trap_request);
1838     DeoptAction action = trap_request_action(trap_request);
1839 #if INCLUDE_JVMCI
1840     int debug_id = trap_request_debug_id(trap_request);
1841 #endif
1842     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1843 
1844     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, current);
1845     compiledVFrame* cvf = compiledVFrame::cast(vf);
1846 
1847     CompiledMethod* nm = cvf->code();
1848 
1849     ScopeDesc*      trap_scope  = cvf->scope();
1850 
1851     bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);
1852 
1853     if (TraceDeoptimization || is_receiver_constraint_failure) {
1854       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
1855 #if INCLUDE_JVMCI
1856           , debug_id
1857 #endif
1858           );
1859     }
1860 
1861     methodHandle    trap_method(current, trap_scope->method());
1862     int             trap_bci    = trap_scope->bci();
1863 #if INCLUDE_JVMCI
1864     jlong           speculation = current->pending_failed_speculation();
1865     if (nm->is_compiled_by_jvmci()) {
1866       nm->as_nmethod()->update_speculation(current);
1867     } else {
1868       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
1869     }
1870 
1871     if (trap_bci == SynchronizationEntryBCI) {
1872       trap_bci = 0;
1873       current->set_pending_monitorenter(true);
1874     }
1875 
1876     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
1877       current->set_pending_transfer_to_interpreter(true);
1878     }
1879 #endif
1880 
1881     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1882     // Record this event in the histogram.
1883     gather_statistics(reason, action, trap_bc);
1884 
1885     // Ensure that we can record deopt. history:
1886     // Need MDO to record RTM code generation state.
1887     bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );
1888 
1889     methodHandle profiled_method;
1890 #if INCLUDE_JVMCI
1891     if (nm->is_compiled_by_jvmci()) {
1892       profiled_method = methodHandle(current, nm->method());
1893     } else {
1894       profiled_method = trap_method;
1895     }
1896 #else
1897     profiled_method = trap_method;
1898 #endif
1899 
1900     MethodData* trap_mdo =
1901       get_method_data(current, profiled_method, create_if_missing);
1902 
1903     JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)
1904 
1905     // Log a message
1906     Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
1907                               trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),
1908                               trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
1909 
1910     // Print a bunch of diagnostics, if requested.
1911     if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {
1912       ResourceMark rm;
1913       ttyLocker ttyl;
1914       char buf[100];
1915       if (xtty != NULL) {
1916         xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
1917                          os::current_thread_id(),
1918                          format_trap_request(buf, sizeof(buf), trap_request));
1919 #if INCLUDE_JVMCI
1920         if (speculation != 0) {
1921           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
1922         }
1923 #endif
1924         nm->log_identity(xtty);
1925       }
1926       Symbol* class_name = NULL;
1927       bool unresolved = false;
1928       if (unloaded_class_index >= 0) {
1929         constantPoolHandle constants (current, trap_method->constants());
1930         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1931           class_name = constants->klass_name_at(unloaded_class_index);
1932           unresolved = true;
1933           if (xtty != NULL)
1934             xtty->print(" unresolved='1'");
1935         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1936           class_name = constants->symbol_at(unloaded_class_index);
1937         }
1938         if (xtty != NULL)
1939           xtty->name(class_name);
1940       }
1941       if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {
1942         // Dump the relevant MDO state.
1943         // This is the deopt count for the current reason, any previous
1944         // reasons or recompiles seen at this point.
1945         int dcnt = trap_mdo->trap_count(reason);
1946         if (dcnt != 0)
1947           xtty->print(" count='%d'", dcnt);
1948         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1949         int dos = (pdata == NULL)? 0: pdata->trap_state();
1950         if (dos != 0) {
1951           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1952           if (trap_state_is_recompiled(dos)) {
1953             int recnt2 = trap_mdo->overflow_recompile_count();
1954             if (recnt2 != 0)
1955               xtty->print(" recompiles2='%d'", recnt2);
1956           }
1957         }
1958       }
1959       if (xtty != NULL) {
1960         xtty->stamp();
1961         xtty->end_head();
1962       }
1963       if (TraceDeoptimization) {  // make noise on the tty
1964         tty->print("Uncommon trap occurred in");
1965         nm->method()->print_short_name(tty);
1966         tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
1967 #if INCLUDE_JVMCI
1968         if (nm->is_nmethod()) {
1969           const char* installed_code_name = nm->as_nmethod()->jvmci_name();
1970           if (installed_code_name != NULL) {
1971             tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);
1972           }
1973         }
1974 #endif
1975         tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
1976                    p2i(fr.pc()),
1977                    os::current_thread_id(),
1978                    trap_reason_name(reason),
1979                    trap_action_name(action),
1980                    unloaded_class_index
1981 #if INCLUDE_JVMCI
1982                    , debug_id
1983 #endif
1984                    );
1985         if (class_name != NULL) {
1986           tty->print(unresolved ? " unresolved class: " : " symbol: ");
1987           class_name->print_symbol_on(tty);
1988         }
1989         tty->cr();
1990       }
1991       if (xtty != NULL) {
1992         // Log the precise location of the trap.
1993         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1994           xtty->begin_elem("jvms bci='%d'", sd->bci());
1995           xtty->method(sd->method());
1996           xtty->end_elem();
1997           if (sd->is_top())  break;
1998         }
1999         xtty->tail("uncommon_trap");
2000       }
2001     }
2002     // (End diagnostic printout.)
2003 
2004     if (is_receiver_constraint_failure) {
2005       fatal("missing receiver type check");
2006     }
2007 
2008     // Load class if necessary
2009     if (unloaded_class_index >= 0) {
2010       constantPoolHandle constants(current, trap_method->constants());
2011       load_class_by_index(constants, unloaded_class_index, THREAD);
2012     }
2013 
2014     // Flush the nmethod if necessary and desirable.
2015     //
2016     // We need to avoid situations where we are re-flushing the nmethod
2017     // because of a hot deoptimization site.  Repeated flushes at the same
2018     // point need to be detected by the compiler and avoided.  If the compiler
2019     // cannot avoid them (or has a bug and "refuses" to avoid them), this
2020     // module must take measures to avoid an infinite cycle of recompilation
2021     // and deoptimization.  There are several such measures:
2022     //
2023     //   1. If a recompilation is ordered a second time at some site X
2024     //   and for the same reason R, the action is adjusted to 'reinterpret',
2025     //   to give the interpreter time to exercise the method more thoroughly.
2026     //   If this happens, the method's overflow_recompile_count is incremented.
2027     //
2028     //   2. If the compiler fails to reduce the deoptimization rate, then
2029     //   the method's overflow_recompile_count will begin to exceed the set
2030     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
2031     //   is adjusted to 'make_not_compilable', and the method is abandoned
2032     //   to the interpreter.  This is a performance hit for hot methods,
2033     //   but is better than a disastrous infinite cycle of recompilations.
2034     //   (Actually, only the method containing the site X is abandoned.)
2035     //
2036     //   3. In parallel with the previous measures, if the total number of
2037     //   recompilations of a method exceeds the much larger set limit
2038     //   PerMethodRecompilationCutoff, the method is abandoned.
2039     //   This should only happen if the method is very large and has
2040     //   many "lukewarm" deoptimizations.  The code which enforces this
2041     //   limit is elsewhere (class nmethod, class Method).
2042     //
2043     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2044     // to recompile at each bytecode independently of the per-BCI cutoff.
2045     //
2046     // The decision to update code is up to the compiler, and is encoded
2047     // in the Action_xxx code.  If the compiler requests Action_none
2048     // no trap state is changed, no compiled code is changed, and the
2049     // computation suffers along in the interpreter.
2050     //
2051     // The other action codes specify various tactics for decompilation
2052     // and recompilation.  Action_maybe_recompile is the loosest, and
2053     // allows the compiled code to stay around until enough traps are seen,
2054     // and until the compiler gets around to recompiling the trapping method.
2055     //
2056     // The other actions cause immediate removal of the present code.
2057 
2058     // Traps caused by injected profile shouldn't pollute trap counts.
2059     bool injected_profile_trap = trap_method->has_injected_profile() &&
2060                                  (reason == Reason_intrinsic || reason == Reason_unreached);
2061 
2062     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2063     bool make_not_entrant = false;
2064     bool make_not_compilable = false;
2065     bool reprofile = false;
2066     switch (action) {
2067     case Action_none:
2068       // Keep the old code.
2069       update_trap_state = false;
2070       break;
2071     case Action_maybe_recompile:
2072       // Do not need to invalidate the present code, but we can
2073       // initiate another
2074       // Start compiler without (necessarily) invalidating the nmethod.
2075       // The system will tolerate the old code, but new code should be
2076       // generated when possible.
2077       break;
2078     case Action_reinterpret:
2079       // Go back into the interpreter for a while, and then consider
2080       // recompiling form scratch.
2081       make_not_entrant = true;
2082       // Reset invocation counter for outer most method.
2083       // This will allow the interpreter to exercise the bytecodes
2084       // for a while before recompiling.
2085       // By contrast, Action_make_not_entrant is immediate.
2086       //
2087       // Note that the compiler will track null_check, null_assert,
2088       // range_check, and class_check events and log them as if they
2089       // had been traps taken from compiled code.  This will update
2090       // the MDO trap history so that the next compilation will
2091       // properly detect hot trap sites.
2092       reprofile = true;
2093       break;
2094     case Action_make_not_entrant:
2095       // Request immediate recompilation, and get rid of the old code.
2096       // Make them not entrant, so next time they are called they get
2097       // recompiled.  Unloaded classes are loaded now so recompile before next
2098       // time they are called.  Same for uninitialized.  The interpreter will
2099       // link the missing class, if any.
2100       make_not_entrant = true;
2101       break;
2102     case Action_make_not_compilable:
2103       // Give up on compiling this method at all.
2104       make_not_entrant = true;
2105       make_not_compilable = true;
2106       break;
2107     default:
2108       ShouldNotReachHere();
2109     }
2110 
2111     // Setting +ProfileTraps fixes the following, on all platforms:
2112     // 4852688: ProfileInterpreter is off by default for ia64.  The result is
2113     // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2114     // recompile relies on a MethodData* to record heroic opt failures.
2115 
2116     // Whether the interpreter is producing MDO data or not, we also need
2117     // to use the MDO to detect hot deoptimization points and control
2118     // aggressive optimization.
2119     bool inc_recompile_count = false;
2120     ProfileData* pdata = NULL;
2121     if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != NULL) {
2122       assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");
2123       uint this_trap_count = 0;
2124       bool maybe_prior_trap = false;
2125       bool maybe_prior_recompile = false;
2126       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2127 #if INCLUDE_JVMCI
2128                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2129 #endif
2130                                    nm->method(),
2131                                    //outputs:
2132                                    this_trap_count,
2133                                    maybe_prior_trap,
2134                                    maybe_prior_recompile);
2135       // Because the interpreter also counts null, div0, range, and class
2136       // checks, these traps from compiled code are double-counted.
2137       // This is harmless; it just means that the PerXTrapLimit values
2138       // are in effect a little smaller than they look.
2139 
2140       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2141       if (per_bc_reason != Reason_none) {
2142         // Now take action based on the partially known per-BCI history.
2143         if (maybe_prior_trap
2144             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2145           // If there are too many traps at this BCI, force a recompile.
2146           // This will allow the compiler to see the limit overflow, and
2147           // take corrective action, if possible.  The compiler generally
2148           // does not use the exact PerBytecodeTrapLimit value, but instead
2149           // changes its tactics if it sees any traps at all.  This provides
2150           // a little hysteresis, delaying a recompile until a trap happens
2151           // several times.
2152           //
2153           // Actually, since there is only one bit of counter per BCI,
2154           // the possible per-BCI counts are {0,1,(per-method count)}.
2155           // This produces accurate results if in fact there is only
2156           // one hot trap site, but begins to get fuzzy if there are
2157           // many sites.  For example, if there are ten sites each
2158           // trapping two or more times, they each get the blame for
2159           // all of their traps.
2160           make_not_entrant = true;
2161         }
2162 
2163         // Detect repeated recompilation at the same BCI, and enforce a limit.
2164         if (make_not_entrant && maybe_prior_recompile) {
2165           // More than one recompile at this point.
2166           inc_recompile_count = maybe_prior_trap;
2167         }
2168       } else {
2169         // For reasons which are not recorded per-bytecode, we simply
2170         // force recompiles unconditionally.
2171         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2172         make_not_entrant = true;
2173       }
2174 
2175       // Go back to the compiler if there are too many traps in this method.
2176       if (this_trap_count >= per_method_trap_limit(reason)) {
2177         // If there are too many traps in this method, force a recompile.
2178         // This will allow the compiler to see the limit overflow, and
2179         // take corrective action, if possible.
2180         // (This condition is an unlikely backstop only, because the
2181         // PerBytecodeTrapLimit is more likely to take effect first,
2182         // if it is applicable.)
2183         make_not_entrant = true;
2184       }
2185 
2186       // Here's more hysteresis:  If there has been a recompile at
2187       // this trap point already, run the method in the interpreter
2188       // for a while to exercise it more thoroughly.
2189       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2190         reprofile = true;
2191       }
2192     }
2193 
2194     // Take requested actions on the method:
2195 
2196     // Recompile
2197     if (make_not_entrant) {
2198       if (!nm->make_not_entrant()) {
2199         return; // the call did not change nmethod's state
2200       }
2201 
2202       if (pdata != NULL) {
2203         // Record the recompilation event, if any.
2204         int tstate0 = pdata->trap_state();
2205         int tstate1 = trap_state_set_recompiled(tstate0, true);
2206         if (tstate1 != tstate0)
2207           pdata->set_trap_state(tstate1);
2208       }
2209 
2210 #if INCLUDE_RTM_OPT
2211       // Restart collecting RTM locking abort statistic if the method
2212       // is recompiled for a reason other than RTM state change.
2213       // Assume that in new recompiled code the statistic could be different,
2214       // for example, due to different inlining.
2215       if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
2216           UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {
2217         trap_mdo->atomic_set_rtm_state(ProfileRTM);
2218       }
2219 #endif
2220       // For code aging we count traps separately here, using make_not_entrant()
2221       // as a guard against simultaneous deopts in multiple threads.
2222       if (reason == Reason_tenured && trap_mdo != NULL) {
2223         trap_mdo->inc_tenure_traps();
2224       }
2225     }
2226 
2227     if (inc_recompile_count) {
2228       trap_mdo->inc_overflow_recompile_count();
2229       if ((uint)trap_mdo->overflow_recompile_count() >
2230           (uint)PerBytecodeRecompilationCutoff) {
2231         // Give up on the method containing the bad BCI.
2232         if (trap_method() == nm->method()) {
2233           make_not_compilable = true;
2234         } else {
2235           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2236           // But give grace to the enclosing nm->method().
2237         }
2238       }
2239     }
2240 
2241     // Reprofile
2242     if (reprofile) {
2243       CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());
2244     }
2245 
2246     // Give up compiling
2247     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2248       assert(make_not_entrant, "consistent");
2249       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2250     }
2251 
2252   } // Free marked resources
2253 
2254 }
2255 JRT_END
2256 
2257 ProfileData*
2258 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2259                                          int trap_bci,
2260                                          Deoptimization::DeoptReason reason,
2261                                          bool update_total_trap_count,
2262 #if INCLUDE_JVMCI
2263                                          bool is_osr,
2264 #endif
2265                                          Method* compiled_method,
2266                                          //outputs:
2267                                          uint& ret_this_trap_count,
2268                                          bool& ret_maybe_prior_trap,
2269                                          bool& ret_maybe_prior_recompile) {
2270   bool maybe_prior_trap = false;
2271   bool maybe_prior_recompile = false;
2272   uint this_trap_count = 0;
2273   if (update_total_trap_count) {
2274     uint idx = reason;
2275 #if INCLUDE_JVMCI
2276     if (is_osr) {
2277       idx += Reason_LIMIT;
2278     }
2279 #endif
2280     uint prior_trap_count = trap_mdo->trap_count(idx);
2281     this_trap_count  = trap_mdo->inc_trap_count(idx);
2282 
2283     // If the runtime cannot find a place to store trap history,
2284     // it is estimated based on the general condition of the method.
2285     // If the method has ever been recompiled, or has ever incurred
2286     // a trap with the present reason , then this BCI is assumed
2287     // (pessimistically) to be the culprit.
2288     maybe_prior_trap      = (prior_trap_count != 0);
2289     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2290   }
2291   ProfileData* pdata = NULL;
2292 
2293 
2294   // For reasons which are recorded per bytecode, we check per-BCI data.
2295   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2296   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2297   if (per_bc_reason != Reason_none) {
2298     // Find the profile data for this BCI.  If there isn't one,
2299     // try to allocate one from the MDO's set of spares.
2300     // This will let us detect a repeated trap at this point.
2301     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
2302 
2303     if (pdata != NULL) {
2304       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2305         if (LogCompilation && xtty != NULL) {
2306           ttyLocker ttyl;
2307           // no more room for speculative traps in this MDO
2308           xtty->elem("speculative_traps_oom");
2309         }
2310       }
2311       // Query the trap state of this profile datum.
2312       int tstate0 = pdata->trap_state();
2313       if (!trap_state_has_reason(tstate0, per_bc_reason))
2314         maybe_prior_trap = false;
2315       if (!trap_state_is_recompiled(tstate0))
2316         maybe_prior_recompile = false;
2317 
2318       // Update the trap state of this profile datum.
2319       int tstate1 = tstate0;
2320       // Record the reason.
2321       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2322       // Store the updated state on the MDO, for next time.
2323       if (tstate1 != tstate0)
2324         pdata->set_trap_state(tstate1);
2325     } else {
2326       if (LogCompilation && xtty != NULL) {
2327         ttyLocker ttyl;
2328         // Missing MDP?  Leave a small complaint in the log.
2329         xtty->elem("missing_mdp bci='%d'", trap_bci);
2330       }
2331     }
2332   }
2333 
2334   // Return results:
2335   ret_this_trap_count = this_trap_count;
2336   ret_maybe_prior_trap = maybe_prior_trap;
2337   ret_maybe_prior_recompile = maybe_prior_recompile;
2338   return pdata;
2339 }
2340 
2341 void
2342 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2343   ResourceMark rm;
2344   // Ignored outputs:
2345   uint ignore_this_trap_count;
2346   bool ignore_maybe_prior_trap;
2347   bool ignore_maybe_prior_recompile;
2348   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2349   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2350   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2351   query_update_method_data(trap_mdo, trap_bci,
2352                            (DeoptReason)reason,
2353                            update_total_counts,
2354 #if INCLUDE_JVMCI
2355                            false,
2356 #endif
2357                            NULL,
2358                            ignore_this_trap_count,
2359                            ignore_maybe_prior_trap,
2360                            ignore_maybe_prior_recompile);
2361 }
2362 
2363 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2364   // Enable WXWrite: current function is called from methods compiled by C2 directly
2365   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2366 
2367   if (TraceDeoptimization) {
2368     tty->print("Uncommon trap ");
2369   }
2370   // Still in Java no safepoints
2371   {
2372     // This enters VM and may safepoint
2373     uncommon_trap_inner(current, trap_request);
2374   }
2375   HandleMark hm(current);
2376   return fetch_unroll_info_helper(current, exec_mode);
2377 }
2378 
2379 // Local derived constants.
2380 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2381 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2382 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2383 
2384 //---------------------------trap_state_reason---------------------------------
2385 Deoptimization::DeoptReason
2386 Deoptimization::trap_state_reason(int trap_state) {
2387   // This assert provides the link between the width of DataLayout::trap_bits
2388   // and the encoding of "recorded" reasons.  It ensures there are enough
2389   // bits to store all needed reasons in the per-BCI MDO profile.
2390   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2391   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2392   trap_state -= recompile_bit;
2393   if (trap_state == DS_REASON_MASK) {
2394     return Reason_many;
2395   } else {
2396     assert((int)Reason_none == 0, "state=0 => Reason_none");
2397     return (DeoptReason)trap_state;
2398   }
2399 }
2400 //-------------------------trap_state_has_reason-------------------------------
2401 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2402   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2403   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2404   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2405   trap_state -= recompile_bit;
2406   if (trap_state == DS_REASON_MASK) {
2407     return -1;  // true, unspecifically (bottom of state lattice)
2408   } else if (trap_state == reason) {
2409     return 1;   // true, definitely
2410   } else if (trap_state == 0) {
2411     return 0;   // false, definitely (top of state lattice)
2412   } else {
2413     return 0;   // false, definitely
2414   }
2415 }
2416 //-------------------------trap_state_add_reason-------------------------------
2417 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2418   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2419   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2420   trap_state -= recompile_bit;
2421   if (trap_state == DS_REASON_MASK) {
2422     return trap_state + recompile_bit;     // already at state lattice bottom
2423   } else if (trap_state == reason) {
2424     return trap_state + recompile_bit;     // the condition is already true
2425   } else if (trap_state == 0) {
2426     return reason + recompile_bit;          // no condition has yet been true
2427   } else {
2428     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2429   }
2430 }
2431 //-----------------------trap_state_is_recompiled------------------------------
2432 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2433   return (trap_state & DS_RECOMPILE_BIT) != 0;
2434 }
2435 //-----------------------trap_state_set_recompiled-----------------------------
2436 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2437   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2438   else    return trap_state & ~DS_RECOMPILE_BIT;
2439 }
2440 //---------------------------format_trap_state---------------------------------
2441 // This is used for debugging and diagnostics, including LogFile output.
2442 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2443                                               int trap_state) {
2444   assert(buflen > 0, "sanity");
2445   DeoptReason reason      = trap_state_reason(trap_state);
2446   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2447   // Re-encode the state from its decoded components.
2448   int decoded_state = 0;
2449   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2450     decoded_state = trap_state_add_reason(decoded_state, reason);
2451   if (recomp_flag)
2452     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2453   // If the state re-encodes properly, format it symbolically.
2454   // Because this routine is used for debugging and diagnostics,
2455   // be robust even if the state is a strange value.
2456   size_t len;
2457   if (decoded_state != trap_state) {
2458     // Random buggy state that doesn't decode??
2459     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2460   } else {
2461     len = jio_snprintf(buf, buflen, "%s%s",
2462                        trap_reason_name(reason),
2463                        recomp_flag ? " recompiled" : "");
2464   }
2465   return buf;
2466 }
2467 
2468 
2469 //--------------------------------statics--------------------------------------
2470 const char* Deoptimization::_trap_reason_name[] = {
2471   // Note:  Keep this in sync. with enum DeoptReason.
2472   "none",
2473   "null_check",
2474   "null_assert" JVMCI_ONLY("_or_unreached0"),
2475   "range_check",
2476   "class_check",
2477   "array_check",
2478   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2479   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2480   "profile_predicate",
2481   "unloaded",
2482   "uninitialized",
2483   "initialized",
2484   "unreached",
2485   "unhandled",
2486   "constraint",
2487   "div0_check",
2488   "age",
2489   "predicate",
2490   "loop_limit_check",
2491   "speculate_class_check",
2492   "speculate_null_check",
2493   "speculate_null_assert",
2494   "rtm_state_change",
2495   "unstable_if",
2496   "unstable_fused_if",
2497   "receiver_constraint",
2498 #if INCLUDE_JVMCI
2499   "aliasing",
2500   "transfer_to_interpreter",
2501   "not_compiled_exception_handler",
2502   "unresolved",
2503   "jsr_mismatch",
2504 #endif
2505   "tenured"
2506 };
2507 const char* Deoptimization::_trap_action_name[] = {
2508   // Note:  Keep this in sync. with enum DeoptAction.
2509   "none",
2510   "maybe_recompile",
2511   "reinterpret",
2512   "make_not_entrant",
2513   "make_not_compilable"
2514 };
2515 
2516 const char* Deoptimization::trap_reason_name(int reason) {
2517   // Check that every reason has a name
2518   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2519 
2520   if (reason == Reason_many)  return "many";
2521   if ((uint)reason < Reason_LIMIT)
2522     return _trap_reason_name[reason];
2523   static char buf[20];
2524   sprintf(buf, "reason%d", reason);
2525   return buf;
2526 }
2527 const char* Deoptimization::trap_action_name(int action) {
2528   // Check that every action has a name
2529   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2530 
2531   if ((uint)action < Action_LIMIT)
2532     return _trap_action_name[action];
2533   static char buf[20];
2534   sprintf(buf, "action%d", action);
2535   return buf;
2536 }
2537 
2538 // This is used for debugging and diagnostics, including LogFile output.
2539 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2540                                                 int trap_request) {
2541   jint unloaded_class_index = trap_request_index(trap_request);
2542   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2543   const char* action = trap_action_name(trap_request_action(trap_request));
2544 #if INCLUDE_JVMCI
2545   int debug_id = trap_request_debug_id(trap_request);
2546 #endif
2547   size_t len;
2548   if (unloaded_class_index < 0) {
2549     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2550                        reason, action
2551 #if INCLUDE_JVMCI
2552                        ,debug_id
2553 #endif
2554                        );
2555   } else {
2556     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2557                        reason, action, unloaded_class_index
2558 #if INCLUDE_JVMCI
2559                        ,debug_id
2560 #endif
2561                        );
2562   }
2563   return buf;
2564 }
2565 
2566 juint Deoptimization::_deoptimization_hist
2567         [Deoptimization::Reason_LIMIT]
2568     [1 + Deoptimization::Action_LIMIT]
2569         [Deoptimization::BC_CASE_LIMIT]
2570   = {0};
2571 
2572 enum {
2573   LSB_BITS = 8,
2574   LSB_MASK = right_n_bits(LSB_BITS)
2575 };
2576 
2577 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2578                                        Bytecodes::Code bc) {
2579   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2580   assert(action >= 0 && action < Action_LIMIT, "oob");
2581   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2582   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2583   juint* cases = _deoptimization_hist[reason][1+action];
2584   juint* bc_counter_addr = NULL;
2585   juint  bc_counter      = 0;
2586   // Look for an unused counter, or an exact match to this BC.
2587   if (bc != Bytecodes::_illegal) {
2588     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2589       juint* counter_addr = &cases[bc_case];
2590       juint  counter = *counter_addr;
2591       if ((counter == 0 && bc_counter_addr == NULL)
2592           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2593         // this counter is either free or is already devoted to this BC
2594         bc_counter_addr = counter_addr;
2595         bc_counter = counter | bc;
2596       }
2597     }
2598   }
2599   if (bc_counter_addr == NULL) {
2600     // Overflow, or no given bytecode.
2601     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2602     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2603   }
2604   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2605 }
2606 
2607 jint Deoptimization::total_deoptimization_count() {
2608   return _deoptimization_hist[Reason_none][0][0];
2609 }
2610 
2611 void Deoptimization::print_statistics() {
2612   juint total = total_deoptimization_count();
2613   juint account = total;
2614   if (total != 0) {
2615     ttyLocker ttyl;
2616     if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
2617     tty->print_cr("Deoptimization traps recorded:");
2618     #define PRINT_STAT_LINE(name, r) \
2619       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2620     PRINT_STAT_LINE("total", total);
2621     // For each non-zero entry in the histogram, print the reason,
2622     // the action, and (if specifically known) the type of bytecode.
2623     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2624       for (int action = 0; action < Action_LIMIT; action++) {
2625         juint* cases = _deoptimization_hist[reason][1+action];
2626         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2627           juint counter = cases[bc_case];
2628           if (counter != 0) {
2629             char name[1*K];
2630             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2631             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2632               bc = Bytecodes::_illegal;
2633             sprintf(name, "%s/%s/%s",
2634                     trap_reason_name(reason),
2635                     trap_action_name(action),
2636                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2637             juint r = counter >> LSB_BITS;
2638             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2639             account -= r;
2640           }
2641         }
2642       }
2643     }
2644     if (account != 0) {
2645       PRINT_STAT_LINE("unaccounted", account);
2646     }
2647     #undef PRINT_STAT_LINE
2648     if (xtty != NULL)  xtty->tail("statistics");
2649   }
2650 }
2651 
2652 #else // COMPILER2_OR_JVMCI
2653 
2654 
2655 // Stubs for C1 only system.
2656 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2657   return false;
2658 }
2659 
2660 const char* Deoptimization::trap_reason_name(int reason) {
2661   return "unknown";
2662 }
2663 
2664 void Deoptimization::print_statistics() {
2665   // no output
2666 }
2667 
2668 void
2669 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2670   // no udpate
2671 }
2672 
2673 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2674   return 0;
2675 }
2676 
2677 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2678                                        Bytecodes::Code bc) {
2679   // no update
2680 }
2681 
2682 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2683                                               int trap_state) {
2684   jio_snprintf(buf, buflen, "#%d", trap_state);
2685   return buf;
2686 }
2687 
2688 #endif // COMPILER2_OR_JVMCI
--- EOF ---