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