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/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/debugInfoRec.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "interpreter/bytecode.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "interpreter/oopMapCache.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/universe.hpp"
  44 #include "oops/constantPool.hpp"
  45 #include "oops/method.hpp"
  46 #include "oops/objArrayKlass.hpp"
  47 #include "oops/objArrayOop.inline.hpp"
  48 #include "oops/oop.inline.hpp"
  49 #include "oops/fieldStreams.inline.hpp"
  50 #include "oops/typeArrayOop.inline.hpp"
  51 #include "oops/verifyOopClosure.hpp"
  52 #include "prims/jvmtiThreadState.hpp"
  53 #include "prims/vectorSupport.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) )) {
 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 #ifndef CC_INTERP
 600     // Regardless of whether we entered this routine with the pending
 601     // popframe condition bit set, we should always clear it now
 602     thread->clear_popframe_condition();
 603 #else
 604     // C++ interpreter will clear has_pending_popframe when it enters
 605     // with method_resume. For deopt_resume2 we clear it now.
 606     if (thread->popframe_forcing_deopt_reexecution())
 607         thread->clear_popframe_condition();
 608 #endif /* CC_INTERP */
 609   }
 610 
 611   // unpack_frames() is called at the end of the deoptimization handler
 612   // and (in C2) at the end of the uncommon trap handler. Note this fact
 613   // so that an asynchronous stack walker can work again. This counter is
 614   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 615   // the beginning of uncommon_trap().
 616   thread->dec_in_deopt_handler();
 617 }
 618 
 619 // Moved from cpu directories because none of the cpus has callee save values.
 620 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 621 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 622 
 623   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 624   // the days we had adapter frames. When we deoptimize a situation where a
 625   // compiled caller calls a compiled caller will have registers it expects
 626   // to survive the call to the callee. If we deoptimize the callee the only
 627   // way we can restore these registers is to have the oldest interpreter
 628   // frame that we create restore these values. That is what this routine
 629   // will accomplish.
 630 
 631   // At the moment we have modified c2 to not have any callee save registers
 632   // so this problem does not exist and this routine is just a place holder.
 633 
 634   assert(f->is_interpreted_frame(), "must be interpreted");
 635 }
 636 
 637 // Return BasicType of value being returned
 638 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 639 
 640   // We are already active in the special DeoptResourceMark any ResourceObj's we
 641   // allocate will be freed at the end of the routine.
 642 
 643   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
 644   // but makes the entry a little slower. There is however a little dance we have to
 645   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
 646   ResetNoHandleMark rnhm; // No-op in release/product versions
 647   HandleMark hm;
 648 
 649   frame stub_frame = thread->last_frame();
 650 
 651   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 652   // must point to the vframeArray for the unpack frame.
 653   vframeArray* array = thread->vframe_array_head();
 654 
 655 #ifndef PRODUCT
 656   if (TraceDeoptimization) {
 657     ttyLocker ttyl;
 658     tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",
 659                   p2i(thread), p2i(array), exec_mode);
 660   }
 661 #endif
 662   Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
 663               p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);
 664 
 665   UnrollBlock* info = array->unroll_block();
 666 
 667   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 668   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 669 
 670   BasicType bt = info->return_type();
 671 
 672   // If we have an exception pending, claim that the return type is an oop
 673   // so the deopt_blob does not overwrite the exception_oop.
 674 
 675   if (exec_mode == Unpack_exception)
 676     bt = T_OBJECT;
 677 
 678   // Cleanup thread deopt data
 679   cleanup_deopt_info(thread, array);
 680 
 681 #ifndef PRODUCT
 682   if (VerifyStack) {
 683     ResourceMark res_mark;
 684     // Clear pending exception to not break verification code (restored afterwards)
 685     PRESERVE_EXCEPTION_MARK;
 686 
 687     thread->validate_frame_layout();
 688 
 689     // Verify that the just-unpacked frames match the interpreter's
 690     // notions of expression stack and locals
 691     vframeArray* cur_array = thread->vframe_array_last();
 692     RegisterMap rm(thread, false);
 693     rm.set_include_argument_oops(false);
 694     bool is_top_frame = true;
 695     int callee_size_of_parameters = 0;
 696     int callee_max_locals = 0;
 697     for (int i = 0; i < cur_array->frames(); i++) {
 698       vframeArrayElement* el = cur_array->element(i);
 699       frame* iframe = el->iframe();
 700       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 701 
 702       // Get the oop map for this bci
 703       InterpreterOopMap mask;
 704       int cur_invoke_parameter_size = 0;
 705       bool try_next_mask = false;
 706       int next_mask_expression_stack_size = -1;
 707       int top_frame_expression_stack_adjustment = 0;
 708       methodHandle mh(thread, iframe->interpreter_frame_method());
 709       OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
 710       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 711       int max_bci = mh->code_size();
 712       // Get to the next bytecode if possible
 713       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 714       // Check to see if we can grab the number of outgoing arguments
 715       // at an uncommon trap for an invoke (where the compiler
 716       // generates debug info before the invoke has executed)
 717       Bytecodes::Code cur_code = str.next();
 718       if (Bytecodes::is_invoke(cur_code)) {
 719         Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
 720         cur_invoke_parameter_size = invoke.size_of_parameters();
 721         if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
 722           callee_size_of_parameters++;
 723         }
 724       }
 725       if (str.bci() < max_bci) {
 726         Bytecodes::Code next_code = str.next();
 727         if (next_code >= 0) {
 728           // The interpreter oop map generator reports results before
 729           // the current bytecode has executed except in the case of
 730           // calls. It seems to be hard to tell whether the compiler
 731           // has emitted debug information matching the "state before"
 732           // a given bytecode or the state after, so we try both
 733           if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) {
 734             // Get expression stack size for the next bytecode
 735             InterpreterOopMap next_mask;
 736             OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
 737             next_mask_expression_stack_size = next_mask.expression_stack_size();
 738             if (Bytecodes::is_invoke(next_code)) {
 739               Bytecode_invoke invoke(mh, str.bci());
 740               next_mask_expression_stack_size += invoke.size_of_parameters();
 741             }
 742             // Need to subtract off the size of the result type of
 743             // the bytecode because this is not described in the
 744             // debug info but returned to the interpreter in the TOS
 745             // caching register
 746             BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
 747             if (bytecode_result_type != T_ILLEGAL) {
 748               top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
 749             }
 750             assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
 751             try_next_mask = true;
 752           }
 753         }
 754       }
 755 
 756       // Verify stack depth and oops in frame
 757       // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
 758       if (!(
 759             /* SPARC */
 760             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
 761             /* x86 */
 762             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
 763             (try_next_mask &&
 764              (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
 765                                                                     top_frame_expression_stack_adjustment))) ||
 766             (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
 767             (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
 768              (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
 769             )) {
 770         {
 771           ttyLocker ttyl;
 772 
 773           // Print out some information that will help us debug the problem
 774           tty->print_cr("Wrong number of expression stack elements during deoptimization");
 775           tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
 776           tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
 777                         iframe->interpreter_frame_expression_stack_size());
 778           tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
 779           tty->print_cr("  try_next_mask = %d", try_next_mask);
 780           tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
 781           tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
 782           tty->print_cr("  callee_max_locals = %d", callee_max_locals);
 783           tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
 784           tty->print_cr("  exec_mode = %d", exec_mode);
 785           tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
 786           tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
 787           tty->print_cr("  Interpreted frames:");
 788           for (int k = 0; k < cur_array->frames(); k++) {
 789             vframeArrayElement* el = cur_array->element(k);
 790             tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
 791           }
 792           cur_array->print_on_2(tty);
 793         } // release tty lock before calling guarantee
 794         guarantee(false, "wrong number of expression stack elements during deopt");
 795       }
 796       VerifyOopClosure verify;
 797       iframe->oops_interpreted_do(&verify, &rm, false);
 798       callee_size_of_parameters = mh->size_of_parameters();
 799       callee_max_locals = mh->max_locals();
 800       is_top_frame = false;
 801     }
 802   }
 803 #endif /* !PRODUCT */
 804 
 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 #ifdef COMPILER2
1006         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1007           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1008         } else {
1009           obj = ik->allocate_instance(THREAD);
1010         }
1011 #else
1012         obj = ik->allocate_instance(THREAD);
1013 #endif // COMPILER2
1014       }
1015     } else if (k->is_typeArray_klass()) {
1016       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1017       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1018       int len = sv->field_size() / type2size[ak->element_type()];
1019       obj = ak->allocate(len, THREAD);
1020     } else if (k->is_objArray_klass()) {
1021       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1022       obj = ak->allocate(sv->field_size(), THREAD);
1023     }
1024 
1025     if (obj == NULL) {
1026       failures = true;
1027     }
1028 
1029     assert(sv->value().is_null(), "redundant reallocation");
1030     assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
1031     CLEAR_PENDING_EXCEPTION;
1032     sv->set_value(obj);
1033   }
1034 
1035   if (failures) {
1036     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1037   } else if (pending_exception.not_null()) {
1038     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1039   }
1040 
1041   return failures;
1042 }
1043 
1044 // restore elements of an eliminated type array
1045 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1046   int index = 0;
1047   intptr_t val;
1048 
1049   for (int i = 0; i < sv->field_size(); i++) {
1050     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1051     switch(type) {
1052     case T_LONG: case T_DOUBLE: {
1053       assert(value->type() == T_INT, "Agreement.");
1054       StackValue* low =
1055         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1056 #ifdef _LP64
1057       jlong res = (jlong)low->get_int();
1058 #else
1059 #ifdef SPARC
1060       // For SPARC we have to swap high and low words.
1061       jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1062 #else
1063       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1064 #endif //SPARC
1065 #endif
1066       obj->long_at_put(index, res);
1067       break;
1068     }
1069 
1070     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1071     case T_INT: case T_FLOAT: { // 4 bytes.
1072       assert(value->type() == T_INT, "Agreement.");
1073       bool big_value = false;
1074       if (i + 1 < sv->field_size() && type == T_INT) {
1075         if (sv->field_at(i)->is_location()) {
1076           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1077           if (type == Location::dbl || type == Location::lng) {
1078             big_value = true;
1079           }
1080         } else if (sv->field_at(i)->is_constant_int()) {
1081           ScopeValue* next_scope_field = sv->field_at(i + 1);
1082           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1083             big_value = true;
1084           }
1085         }
1086       }
1087 
1088       if (big_value) {
1089         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1090   #ifdef _LP64
1091         jlong res = (jlong)low->get_int();
1092   #else
1093   #ifdef SPARC
1094         // For SPARC we have to swap high and low words.
1095         jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1096   #else
1097         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1098   #endif //SPARC
1099   #endif
1100         obj->int_at_put(index, (jint)*((jint*)&res));
1101         obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
1102       } else {
1103         val = value->get_int();
1104         obj->int_at_put(index, (jint)*((jint*)&val));
1105       }
1106       break;
1107     }
1108 
1109     case T_SHORT:
1110       assert(value->type() == T_INT, "Agreement.");
1111       val = value->get_int();
1112       obj->short_at_put(index, (jshort)*((jint*)&val));
1113       break;
1114 
1115     case T_CHAR:
1116       assert(value->type() == T_INT, "Agreement.");
1117       val = value->get_int();
1118       obj->char_at_put(index, (jchar)*((jint*)&val));
1119       break;
1120 
1121     case T_BYTE:
1122       assert(value->type() == T_INT, "Agreement.");
1123       val = value->get_int();
1124       obj->byte_at_put(index, (jbyte)*((jint*)&val));
1125       break;
1126 
1127     case T_BOOLEAN:
1128       assert(value->type() == T_INT, "Agreement.");
1129       val = value->get_int();
1130       obj->bool_at_put(index, (jboolean)*((jint*)&val));
1131       break;
1132 
1133       default:
1134         ShouldNotReachHere();
1135     }
1136     index++;
1137   }
1138 }
1139 
1140 
1141 // restore fields of an eliminated object array
1142 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1143   for (int i = 0; i < sv->field_size(); i++) {
1144     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1145     assert(value->type() == T_OBJECT, "object element expected");
1146     obj->obj_at_put(i, value->get_obj()());
1147   }
1148 }
1149 
1150 class ReassignedField {
1151 public:
1152   int _offset;
1153   BasicType _type;
1154 public:
1155   ReassignedField() {
1156     _offset = 0;
1157     _type = T_ILLEGAL;
1158   }
1159 };
1160 
1161 int compare(ReassignedField* left, ReassignedField* right) {
1162   return left->_offset - right->_offset;
1163 }
1164 
1165 // Restore fields of an eliminated instance object using the same field order
1166 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
1167 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
1168   GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
1169   InstanceKlass* ik = klass;
1170   while (ik != NULL) {
1171     for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1172       if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
1173         ReassignedField field;
1174         field._offset = fs.offset();
1175         field._type = Signature::basic_type(fs.signature());
1176         fields->append(field);
1177       }
1178     }
1179     ik = ik->superklass();
1180   }
1181   fields->sort(compare);
1182   for (int i = 0; i < fields->length(); i++) {
1183     intptr_t val;
1184     ScopeValue* scope_field = sv->field_at(svIndex);
1185     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1186     int offset = fields->at(i)._offset;
1187     BasicType type = fields->at(i)._type;
1188     switch (type) {
1189       case T_OBJECT: case T_ARRAY:
1190         assert(value->type() == T_OBJECT, "Agreement.");
1191         obj->obj_field_put(offset, value->get_obj()());
1192         break;
1193 
1194       // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1195       case T_INT: case T_FLOAT: { // 4 bytes.
1196         assert(value->type() == T_INT, "Agreement.");
1197         bool big_value = false;
1198         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1199           if (scope_field->is_location()) {
1200             Location::Type type = ((LocationValue*) scope_field)->location().type();
1201             if (type == Location::dbl || type == Location::lng) {
1202               big_value = true;
1203             }
1204           }
1205           if (scope_field->is_constant_int()) {
1206             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1207             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1208               big_value = true;
1209             }
1210           }
1211         }
1212 
1213         if (big_value) {
1214           i++;
1215           assert(i < fields->length(), "second T_INT field needed");
1216           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1217         } else {
1218           val = value->get_int();
1219           obj->int_field_put(offset, (jint)*((jint*)&val));
1220           break;
1221         }
1222       }
1223         /* no break */
1224 
1225       case T_LONG: case T_DOUBLE: {
1226         assert(value->type() == T_INT, "Agreement.");
1227         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1228 #ifdef _LP64
1229         jlong res = (jlong)low->get_int();
1230 #else
1231 #ifdef SPARC
1232         // For SPARC we have to swap high and low words.
1233         jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1234 #else
1235         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1236 #endif //SPARC
1237 #endif
1238         obj->long_field_put(offset, res);
1239         break;
1240       }
1241 
1242       case T_SHORT:
1243         assert(value->type() == T_INT, "Agreement.");
1244         val = value->get_int();
1245         obj->short_field_put(offset, (jshort)*((jint*)&val));
1246         break;
1247 
1248       case T_CHAR:
1249         assert(value->type() == T_INT, "Agreement.");
1250         val = value->get_int();
1251         obj->char_field_put(offset, (jchar)*((jint*)&val));
1252         break;
1253 
1254       case T_BYTE:
1255         assert(value->type() == T_INT, "Agreement.");
1256         val = value->get_int();
1257         obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1258         break;
1259 
1260       case T_BOOLEAN:
1261         assert(value->type() == T_INT, "Agreement.");
1262         val = value->get_int();
1263         obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1264         break;
1265 
1266       default:
1267         ShouldNotReachHere();
1268     }
1269     svIndex++;
1270   }
1271   return svIndex;
1272 }
1273 
1274 // restore fields of all eliminated objects and arrays
1275 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
1276   for (int i = 0; i < objects->length(); i++) {
1277     ObjectValue* sv = (ObjectValue*) objects->at(i);
1278     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1279     Handle obj = sv->value();
1280     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1281     if (PrintDeoptimizationDetails) {
1282       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1283     }
1284     if (obj.is_null()) {
1285       continue;
1286     }
1287 #if INCLUDE_JVMCI || INCLUDE_AOT
1288     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1289     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1290       continue;
1291     }
1292 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1293 #ifdef COMPILER2
1294     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1295       continue; // skip field reassignment for vectors
1296     }
1297 #endif
1298     if (k->is_instance_klass()) {
1299       InstanceKlass* ik = InstanceKlass::cast(k);
1300       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);
1301     } else if (k->is_typeArray_klass()) {
1302       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1303       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1304     } else if (k->is_objArray_klass()) {
1305       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1306     }
1307   }
1308 }
1309 
1310 
1311 // relock objects for which synchronization was eliminated
1312 void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
1313   for (int i = 0; i < monitors->length(); i++) {
1314     MonitorInfo* mon_info = monitors->at(i);
1315     if (mon_info->eliminated()) {
1316       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1317       if (!mon_info->owner_is_scalar_replaced()) {
1318         Handle obj(thread, mon_info->owner());
1319         markWord mark = obj->mark();
1320         if (UseBiasedLocking && mark.has_bias_pattern()) {
1321           // New allocated objects may have the mark set to anonymously biased.
1322           // Also the deoptimized method may called methods with synchronization
1323           // where the thread-local object is bias locked to the current thread.
1324           assert(mark.is_biased_anonymously() ||
1325                  mark.biased_locker() == thread, "should be locked to current thread");
1326           // Reset mark word to unbiased prototype.
1327           markWord unbiased_prototype = markWord::prototype().set_age(mark.age());
1328           obj->set_mark(unbiased_prototype);
1329         }
1330         BasicLock* lock = mon_info->lock();
1331         ObjectSynchronizer::enter(obj, lock, thread);
1332         assert(mon_info->owner()->is_locked(), "object must be locked now");
1333       }
1334     }
1335   }
1336 }
1337 
1338 
1339 #ifndef PRODUCT
1340 // print information about reallocated objects
1341 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
1342   fieldDescriptor fd;
1343 
1344   for (int i = 0; i < objects->length(); i++) {
1345     ObjectValue* sv = (ObjectValue*) objects->at(i);
1346     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1347     Handle obj = sv->value();
1348 
1349     tty->print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
1350     k->print_value();
1351     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1352     if (obj.is_null()) {
1353       tty->print(" allocation failed");
1354     } else {
1355       tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
1356     }
1357     tty->cr();
1358 
1359     if (Verbose && !obj.is_null()) {
1360       k->oop_print_on(obj(), tty);
1361     }
1362   }
1363 }
1364 #endif
1365 #endif // COMPILER2_OR_JVMCI
1366 
1367 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1368   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1369 
1370 #ifndef PRODUCT
1371   if (PrintDeoptimizationDetails) {
1372     ttyLocker ttyl;
1373     tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));
1374     fr.print_on(tty);
1375     tty->print_cr("     Virtual frames (innermost first):");
1376     for (int index = 0; index < chunk->length(); index++) {
1377       compiledVFrame* vf = chunk->at(index);
1378       tty->print("       %2d - ", index);
1379       vf->print_value();
1380       int bci = chunk->at(index)->raw_bci();
1381       const char* code_name;
1382       if (bci == SynchronizationEntryBCI) {
1383         code_name = "sync entry";
1384       } else {
1385         Bytecodes::Code code = vf->method()->code_at(bci);
1386         code_name = Bytecodes::name(code);
1387       }
1388       tty->print(" - %s", code_name);
1389       tty->print_cr(" @ bci %d ", bci);
1390       if (Verbose) {
1391         vf->print();
1392         tty->cr();
1393       }
1394     }
1395   }
1396 #endif
1397 
1398   // Register map for next frame (used for stack crawl).  We capture
1399   // the state of the deopt'ing frame's caller.  Thus if we need to
1400   // stuff a C2I adapter we can properly fill in the callee-save
1401   // register locations.
1402   frame caller = fr.sender(reg_map);
1403   int frame_size = caller.sp() - fr.sp();
1404 
1405   frame sender = caller;
1406 
1407   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1408   // the vframeArray containing the unpacking information is allocated in the C heap.
1409   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1410   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1411 
1412   // Compare the vframeArray to the collected vframes
1413   assert(array->structural_compare(thread, chunk), "just checking");
1414 
1415 #ifndef PRODUCT
1416   if (PrintDeoptimizationDetails) {
1417     ttyLocker ttyl;
1418     tty->print_cr("     Created vframeArray " INTPTR_FORMAT, p2i(array));
1419   }
1420 #endif // PRODUCT
1421 
1422   return array;
1423 }
1424 
1425 #if COMPILER2_OR_JVMCI
1426 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1427   // Reallocation of some scalar replaced objects failed. Record
1428   // that we need to pop all the interpreter frames for the
1429   // deoptimized compiled frame.
1430   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1431   thread->set_frames_to_pop_failed_realloc(array->frames());
1432   // Unlock all monitors here otherwise the interpreter will see a
1433   // mix of locked and unlocked monitors (because of failed
1434   // reallocations of synchronized objects) and be confused.
1435   for (int i = 0; i < array->frames(); i++) {
1436     MonitorChunk* monitors = array->element(i)->monitors();
1437     if (monitors != NULL) {
1438       for (int j = 0; j < monitors->number_of_monitors(); j++) {
1439         BasicObjectLock* src = monitors->at(j);
1440         if (src->obj() != NULL) {
1441           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1442         }
1443       }
1444       array->element(i)->free_monitors(thread);
1445 #ifdef ASSERT
1446       array->element(i)->set_removed_monitors();
1447 #endif
1448     }
1449   }
1450 }
1451 #endif
1452 
1453 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
1454   GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1455   Thread* thread = Thread::current();
1456   for (int i = 0; i < monitors->length(); i++) {
1457     MonitorInfo* mon_info = monitors->at(i);
1458     if (!mon_info->eliminated() && mon_info->owner() != NULL) {
1459       objects_to_revoke->append(Handle(thread, mon_info->owner()));
1460     }
1461   }
1462 }
1463 
1464 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, frame fr, RegisterMap* map) {
1465   // Unfortunately we don't have a RegisterMap available in most of
1466   // the places we want to call this routine so we need to walk the
1467   // stack again to update the register map.
1468   if (map == NULL || !map->update_map()) {
1469     StackFrameStream sfs(thread, true);
1470     bool found = false;
1471     while (!found && !sfs.is_done()) {
1472       frame* cur = sfs.current();
1473       sfs.next();
1474       found = cur->id() == fr.id();
1475     }
1476     assert(found, "frame to be deoptimized not found on target thread's stack");
1477     map = sfs.register_map();
1478   }
1479 
1480   vframe* vf = vframe::new_vframe(&fr, map, thread);
1481   compiledVFrame* cvf = compiledVFrame::cast(vf);
1482   // Revoke monitors' biases in all scopes
1483   while (!cvf->is_top()) {
1484     collect_monitors(cvf, objects_to_revoke);
1485     cvf = compiledVFrame::cast(cvf->sender());
1486   }
1487   collect_monitors(cvf, objects_to_revoke);
1488 }
1489 
1490 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) {
1491   if (!UseBiasedLocking) {
1492     return;
1493   }
1494   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1495   get_monitors_from_stack(objects_to_revoke, thread, fr, map);
1496 
1497   int len = objects_to_revoke->length();
1498   for (int i = 0; i < len; i++) {
1499     oop obj = (objects_to_revoke->at(i))();
1500     BiasedLocking::revoke_own_lock(objects_to_revoke->at(i), thread);
1501     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
1502   }
1503 }
1504 
1505 
1506 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1507   assert(fr.can_be_deoptimized(), "checking frame type");
1508 
1509   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1510 
1511   if (LogCompilation && xtty != NULL) {
1512     CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();
1513     assert(cm != NULL, "only compiled methods can deopt");
1514 
1515     ttyLocker ttyl;
1516     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1517     cm->log_identity(xtty);
1518     xtty->end_head();
1519     for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1520       xtty->begin_elem("jvms bci='%d'", sd->bci());
1521       xtty->method(sd->method());
1522       xtty->end_elem();
1523       if (sd->is_top())  break;
1524     }
1525     xtty->tail("deoptimized");
1526   }
1527 
1528   // Patch the compiled method so that when execution returns to it we will
1529   // deopt the execution state and return to the interpreter.
1530   fr.deoptimize(thread);
1531 }
1532 
1533 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1534   // Deoptimize only if the frame comes from compile code.
1535   // Do not deoptimize the frame which is already patched
1536   // during the execution of the loops below.
1537   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1538     return;
1539   }
1540   ResourceMark rm;
1541   DeoptimizationMarker dm;
1542   deoptimize_single_frame(thread, fr, reason);
1543 }
1544 
1545 #if INCLUDE_JVMCI
1546 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {
1547   // there is no exception handler for this pc => deoptimize
1548   cm->make_not_entrant();
1549 
1550   // Use Deoptimization::deoptimize for all of its side-effects:
1551   // gathering traps statistics, logging...
1552   // it also patches the return pc but we do not care about that
1553   // since we return a continuation to the deopt_blob below.
1554   JavaThread* thread = JavaThread::current();
1555   RegisterMap reg_map(thread, false);
1556   frame runtime_frame = thread->last_frame();
1557   frame caller_frame = runtime_frame.sender(&reg_map);
1558   assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");
1559   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1560 
1561   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);
1562   if (trap_mdo != NULL) {
1563     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1564   }
1565 
1566   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1567 }
1568 #endif
1569 
1570 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1571   assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1572          "can only deoptimize other thread at a safepoint");
1573   // Compute frame and register map based on thread and sp.
1574   RegisterMap reg_map(thread, false);
1575   frame fr = thread->last_frame();
1576   while (fr.id() != id) {
1577     fr = fr.sender(&reg_map);
1578   }
1579   deoptimize(thread, fr, reason);
1580 }
1581 
1582 
1583 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1584   if (thread == Thread::current()) {
1585     Deoptimization::deoptimize_frame_internal(thread, id, reason);
1586   } else {
1587     VM_DeoptimizeFrame deopt(thread, id, reason);
1588     VMThread::execute(&deopt);
1589   }
1590 }
1591 
1592 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1593   deoptimize_frame(thread, id, Reason_constraint);
1594 }
1595 
1596 // JVMTI PopFrame support
1597 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1598 {
1599   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1600 }
1601 JRT_END
1602 
1603 MethodData*
1604 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1605                                 bool create_if_missing) {
1606   Thread* THREAD = thread;
1607   MethodData* mdo = m()->method_data();
1608   if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1609     // Build an MDO.  Ignore errors like OutOfMemory;
1610     // that simply means we won't have an MDO to update.
1611     Method::build_interpreter_method_data(m, THREAD);
1612     if (HAS_PENDING_EXCEPTION) {
1613       assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1614       CLEAR_PENDING_EXCEPTION;
1615     }
1616     mdo = m()->method_data();
1617   }
1618   return mdo;
1619 }
1620 
1621 #if COMPILER2_OR_JVMCI
1622 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1623   // In case of an unresolved klass entry, load the class.
1624   // This path is exercised from case _ldc in Parse::do_one_bytecode,
1625   // and probably nowhere else.
1626   // Even that case would benefit from simply re-interpreting the
1627   // bytecode, without paying special attention to the class index.
1628   // So this whole "class index" feature should probably be removed.
1629 
1630   if (constant_pool->tag_at(index).is_unresolved_klass()) {
1631     Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK);
1632     return;
1633   }
1634 
1635   assert(!constant_pool->tag_at(index).is_symbol(),
1636          "no symbolic names here, please");
1637 }
1638 
1639 
1640 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) {
1641   EXCEPTION_MARK;
1642   load_class_by_index(constant_pool, index, THREAD);
1643   if (HAS_PENDING_EXCEPTION) {
1644     // Exception happened during classloading. We ignore the exception here, since it
1645     // is going to be rethrown since the current activation is going to be deoptimized and
1646     // the interpreter will re-execute the bytecode.
1647     CLEAR_PENDING_EXCEPTION;
1648     // Class loading called java code which may have caused a stack
1649     // overflow. If the exception was thrown right before the return
1650     // to the runtime the stack is no longer guarded. Reguard the
1651     // stack otherwise if we return to the uncommon trap blob and the
1652     // stack bang causes a stack overflow we crash.
1653     assert(THREAD->is_Java_thread(), "only a java thread can be here");
1654     JavaThread* thread = (JavaThread*)THREAD;
1655     bool guard_pages_enabled = thread->stack_guards_enabled();
1656     if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
1657     assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1658   }
1659 }
1660 
1661 #if INCLUDE_JFR
1662 
1663 class DeoptReasonSerializer : public JfrSerializer {
1664  public:
1665   void serialize(JfrCheckpointWriter& writer) {
1666     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1667     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1668       writer.write_key((u8)i);
1669       writer.write(Deoptimization::trap_reason_name(i));
1670     }
1671   }
1672 };
1673 
1674 class DeoptActionSerializer : public JfrSerializer {
1675  public:
1676   void serialize(JfrCheckpointWriter& writer) {
1677     static const u4 nof_actions = Deoptimization::Action_LIMIT;
1678     writer.write_count(nof_actions);
1679     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1680       writer.write_key(i);
1681       writer.write(Deoptimization::trap_action_name((int)i));
1682     }
1683   }
1684 };
1685 
1686 static void register_serializers() {
1687   static int critical_section = 0;
1688   if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
1689     return;
1690   }
1691   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1692   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1693 }
1694 
1695 static void post_deoptimization_event(CompiledMethod* nm,
1696                                       const Method* method,
1697                                       int trap_bci,
1698                                       int instruction,
1699                                       Deoptimization::DeoptReason reason,
1700                                       Deoptimization::DeoptAction action) {
1701   assert(nm != NULL, "invariant");
1702   assert(method != NULL, "invariant");
1703   if (EventDeoptimization::is_enabled()) {
1704     static bool serializers_registered = false;
1705     if (!serializers_registered) {
1706       register_serializers();
1707       serializers_registered = true;
1708     }
1709     EventDeoptimization event;
1710     event.set_compileId(nm->compile_id());
1711     event.set_compiler(nm->compiler_type());
1712     event.set_method(method);
1713     event.set_lineNumber(method->line_number_from_bci(trap_bci));
1714     event.set_bci(trap_bci);
1715     event.set_instruction(instruction);
1716     event.set_reason(reason);
1717     event.set_action(action);
1718     event.commit();
1719   }
1720 }
1721 
1722 #endif // INCLUDE_JFR
1723 
1724 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1725   HandleMark hm;
1726 
1727   // uncommon_trap() is called at the beginning of the uncommon trap
1728   // handler. Note this fact before we start generating temporary frames
1729   // that can confuse an asynchronous stack walker. This counter is
1730   // decremented at the end of unpack_frames().
1731   thread->inc_in_deopt_handler();
1732 
1733   // We need to update the map if we have biased locking.
1734 #if INCLUDE_JVMCI
1735   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
1736   RegisterMap reg_map(thread, true);
1737 #else
1738   RegisterMap reg_map(thread, UseBiasedLocking);
1739 #endif
1740   frame stub_frame = thread->last_frame();
1741   frame fr = stub_frame.sender(&reg_map);
1742   // Make sure the calling nmethod is not getting deoptimized and removed
1743   // before we are done with it.
1744   nmethodLocker nl(fr.pc());
1745 
1746   // Log a message
1747   Events::log_deopt_message(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
1748               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
1749 
1750   {
1751     ResourceMark rm;
1752 
1753     DeoptReason reason = trap_request_reason(trap_request);
1754     DeoptAction action = trap_request_action(trap_request);
1755 #if INCLUDE_JVMCI
1756     int debug_id = trap_request_debug_id(trap_request);
1757 #endif
1758     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1759 
1760     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
1761     compiledVFrame* cvf = compiledVFrame::cast(vf);
1762 
1763     CompiledMethod* nm = cvf->code();
1764 
1765     ScopeDesc*      trap_scope  = cvf->scope();
1766 
1767     if (TraceDeoptimization) {
1768       ttyLocker ttyl;
1769       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()
1770 #if INCLUDE_JVMCI
1771           , debug_id
1772 #endif
1773           );
1774     }
1775 
1776     methodHandle    trap_method(THREAD, trap_scope->method());
1777     int             trap_bci    = trap_scope->bci();
1778 #if INCLUDE_JVMCI
1779     jlong           speculation = thread->pending_failed_speculation();
1780     if (nm->is_compiled_by_jvmci() && nm->is_nmethod()) { // Exclude AOTed methods
1781       nm->as_nmethod()->update_speculation(thread);
1782     } else {
1783       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
1784     }
1785 
1786     if (trap_bci == SynchronizationEntryBCI) {
1787       trap_bci = 0;
1788       thread->set_pending_monitorenter(true);
1789     }
1790 
1791     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
1792       thread->set_pending_transfer_to_interpreter(true);
1793     }
1794 #endif
1795 
1796     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1797     // Record this event in the histogram.
1798     gather_statistics(reason, action, trap_bc);
1799 
1800     // Ensure that we can record deopt. history:
1801     // Need MDO to record RTM code generation state.
1802     bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );
1803 
1804     methodHandle profiled_method;
1805 #if INCLUDE_JVMCI
1806     if (nm->is_compiled_by_jvmci()) {
1807       profiled_method = methodHandle(THREAD, nm->method());
1808     } else {
1809       profiled_method = trap_method;
1810     }
1811 #else
1812     profiled_method = trap_method;
1813 #endif
1814 
1815     MethodData* trap_mdo =
1816       get_method_data(thread, profiled_method, create_if_missing);
1817 
1818     JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)
1819 
1820     // Log a message
1821     Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
1822                               trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),
1823                               trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
1824 
1825     // Print a bunch of diagnostics, if requested.
1826     if (TraceDeoptimization || LogCompilation) {
1827       ResourceMark rm;
1828       ttyLocker ttyl;
1829       char buf[100];
1830       if (xtty != NULL) {
1831         xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
1832                          os::current_thread_id(),
1833                          format_trap_request(buf, sizeof(buf), trap_request));
1834 #if INCLUDE_JVMCI
1835         if (speculation != 0) {
1836           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
1837         }
1838 #endif
1839         nm->log_identity(xtty);
1840       }
1841       Symbol* class_name = NULL;
1842       bool unresolved = false;
1843       if (unloaded_class_index >= 0) {
1844         constantPoolHandle constants (THREAD, trap_method->constants());
1845         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1846           class_name = constants->klass_name_at(unloaded_class_index);
1847           unresolved = true;
1848           if (xtty != NULL)
1849             xtty->print(" unresolved='1'");
1850         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1851           class_name = constants->symbol_at(unloaded_class_index);
1852         }
1853         if (xtty != NULL)
1854           xtty->name(class_name);
1855       }
1856       if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {
1857         // Dump the relevant MDO state.
1858         // This is the deopt count for the current reason, any previous
1859         // reasons or recompiles seen at this point.
1860         int dcnt = trap_mdo->trap_count(reason);
1861         if (dcnt != 0)
1862           xtty->print(" count='%d'", dcnt);
1863         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1864         int dos = (pdata == NULL)? 0: pdata->trap_state();
1865         if (dos != 0) {
1866           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1867           if (trap_state_is_recompiled(dos)) {
1868             int recnt2 = trap_mdo->overflow_recompile_count();
1869             if (recnt2 != 0)
1870               xtty->print(" recompiles2='%d'", recnt2);
1871           }
1872         }
1873       }
1874       if (xtty != NULL) {
1875         xtty->stamp();
1876         xtty->end_head();
1877       }
1878       if (TraceDeoptimization) {  // make noise on the tty
1879         tty->print("Uncommon trap occurred in");
1880         nm->method()->print_short_name(tty);
1881         tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
1882 #if INCLUDE_JVMCI
1883         if (nm->is_nmethod()) {
1884           const char* installed_code_name = nm->as_nmethod()->jvmci_name();
1885           if (installed_code_name != NULL) {
1886             tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);
1887           }
1888         }
1889 #endif
1890         tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
1891                    p2i(fr.pc()),
1892                    os::current_thread_id(),
1893                    trap_reason_name(reason),
1894                    trap_action_name(action),
1895                    unloaded_class_index
1896 #if INCLUDE_JVMCI
1897                    , debug_id
1898 #endif
1899                    );
1900         if (class_name != NULL) {
1901           tty->print(unresolved ? " unresolved class: " : " symbol: ");
1902           class_name->print_symbol_on(tty);
1903         }
1904         tty->cr();
1905       }
1906       if (xtty != NULL) {
1907         // Log the precise location of the trap.
1908         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1909           xtty->begin_elem("jvms bci='%d'", sd->bci());
1910           xtty->method(sd->method());
1911           xtty->end_elem();
1912           if (sd->is_top())  break;
1913         }
1914         xtty->tail("uncommon_trap");
1915       }
1916     }
1917     // (End diagnostic printout.)
1918 
1919     // Load class if necessary
1920     if (unloaded_class_index >= 0) {
1921       constantPoolHandle constants(THREAD, trap_method->constants());
1922       load_class_by_index(constants, unloaded_class_index);
1923     }
1924 
1925     // Flush the nmethod if necessary and desirable.
1926     //
1927     // We need to avoid situations where we are re-flushing the nmethod
1928     // because of a hot deoptimization site.  Repeated flushes at the same
1929     // point need to be detected by the compiler and avoided.  If the compiler
1930     // cannot avoid them (or has a bug and "refuses" to avoid them), this
1931     // module must take measures to avoid an infinite cycle of recompilation
1932     // and deoptimization.  There are several such measures:
1933     //
1934     //   1. If a recompilation is ordered a second time at some site X
1935     //   and for the same reason R, the action is adjusted to 'reinterpret',
1936     //   to give the interpreter time to exercise the method more thoroughly.
1937     //   If this happens, the method's overflow_recompile_count is incremented.
1938     //
1939     //   2. If the compiler fails to reduce the deoptimization rate, then
1940     //   the method's overflow_recompile_count will begin to exceed the set
1941     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
1942     //   is adjusted to 'make_not_compilable', and the method is abandoned
1943     //   to the interpreter.  This is a performance hit for hot methods,
1944     //   but is better than a disastrous infinite cycle of recompilations.
1945     //   (Actually, only the method containing the site X is abandoned.)
1946     //
1947     //   3. In parallel with the previous measures, if the total number of
1948     //   recompilations of a method exceeds the much larger set limit
1949     //   PerMethodRecompilationCutoff, the method is abandoned.
1950     //   This should only happen if the method is very large and has
1951     //   many "lukewarm" deoptimizations.  The code which enforces this
1952     //   limit is elsewhere (class nmethod, class Method).
1953     //
1954     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
1955     // to recompile at each bytecode independently of the per-BCI cutoff.
1956     //
1957     // The decision to update code is up to the compiler, and is encoded
1958     // in the Action_xxx code.  If the compiler requests Action_none
1959     // no trap state is changed, no compiled code is changed, and the
1960     // computation suffers along in the interpreter.
1961     //
1962     // The other action codes specify various tactics for decompilation
1963     // and recompilation.  Action_maybe_recompile is the loosest, and
1964     // allows the compiled code to stay around until enough traps are seen,
1965     // and until the compiler gets around to recompiling the trapping method.
1966     //
1967     // The other actions cause immediate removal of the present code.
1968 
1969     // Traps caused by injected profile shouldn't pollute trap counts.
1970     bool injected_profile_trap = trap_method->has_injected_profile() &&
1971                                  (reason == Reason_intrinsic || reason == Reason_unreached);
1972 
1973     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
1974     bool make_not_entrant = false;
1975     bool make_not_compilable = false;
1976     bool reprofile = false;
1977     switch (action) {
1978     case Action_none:
1979       // Keep the old code.
1980       update_trap_state = false;
1981       break;
1982     case Action_maybe_recompile:
1983       // Do not need to invalidate the present code, but we can
1984       // initiate another
1985       // Start compiler without (necessarily) invalidating the nmethod.
1986       // The system will tolerate the old code, but new code should be
1987       // generated when possible.
1988       break;
1989     case Action_reinterpret:
1990       // Go back into the interpreter for a while, and then consider
1991       // recompiling form scratch.
1992       make_not_entrant = true;
1993       // Reset invocation counter for outer most method.
1994       // This will allow the interpreter to exercise the bytecodes
1995       // for a while before recompiling.
1996       // By contrast, Action_make_not_entrant is immediate.
1997       //
1998       // Note that the compiler will track null_check, null_assert,
1999       // range_check, and class_check events and log them as if they
2000       // had been traps taken from compiled code.  This will update
2001       // the MDO trap history so that the next compilation will
2002       // properly detect hot trap sites.
2003       reprofile = true;
2004       break;
2005     case Action_make_not_entrant:
2006       // Request immediate recompilation, and get rid of the old code.
2007       // Make them not entrant, so next time they are called they get
2008       // recompiled.  Unloaded classes are loaded now so recompile before next
2009       // time they are called.  Same for uninitialized.  The interpreter will
2010       // link the missing class, if any.
2011       make_not_entrant = true;
2012       break;
2013     case Action_make_not_compilable:
2014       // Give up on compiling this method at all.
2015       make_not_entrant = true;
2016       make_not_compilable = true;
2017       break;
2018     default:
2019       ShouldNotReachHere();
2020     }
2021 
2022     // Setting +ProfileTraps fixes the following, on all platforms:
2023     // 4852688: ProfileInterpreter is off by default for ia64.  The result is
2024     // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2025     // recompile relies on a MethodData* to record heroic opt failures.
2026 
2027     // Whether the interpreter is producing MDO data or not, we also need
2028     // to use the MDO to detect hot deoptimization points and control
2029     // aggressive optimization.
2030     bool inc_recompile_count = false;
2031     ProfileData* pdata = NULL;
2032     if (ProfileTraps && !is_client_compilation_mode_vm() && update_trap_state && trap_mdo != NULL) {
2033       assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity");
2034       uint this_trap_count = 0;
2035       bool maybe_prior_trap = false;
2036       bool maybe_prior_recompile = false;
2037       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2038 #if INCLUDE_JVMCI
2039                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2040 #endif
2041                                    nm->method(),
2042                                    //outputs:
2043                                    this_trap_count,
2044                                    maybe_prior_trap,
2045                                    maybe_prior_recompile);
2046       // Because the interpreter also counts null, div0, range, and class
2047       // checks, these traps from compiled code are double-counted.
2048       // This is harmless; it just means that the PerXTrapLimit values
2049       // are in effect a little smaller than they look.
2050 
2051       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2052       if (per_bc_reason != Reason_none) {
2053         // Now take action based on the partially known per-BCI history.
2054         if (maybe_prior_trap
2055             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2056           // If there are too many traps at this BCI, force a recompile.
2057           // This will allow the compiler to see the limit overflow, and
2058           // take corrective action, if possible.  The compiler generally
2059           // does not use the exact PerBytecodeTrapLimit value, but instead
2060           // changes its tactics if it sees any traps at all.  This provides
2061           // a little hysteresis, delaying a recompile until a trap happens
2062           // several times.
2063           //
2064           // Actually, since there is only one bit of counter per BCI,
2065           // the possible per-BCI counts are {0,1,(per-method count)}.
2066           // This produces accurate results if in fact there is only
2067           // one hot trap site, but begins to get fuzzy if there are
2068           // many sites.  For example, if there are ten sites each
2069           // trapping two or more times, they each get the blame for
2070           // all of their traps.
2071           make_not_entrant = true;
2072         }
2073 
2074         // Detect repeated recompilation at the same BCI, and enforce a limit.
2075         if (make_not_entrant && maybe_prior_recompile) {
2076           // More than one recompile at this point.
2077           inc_recompile_count = maybe_prior_trap;
2078         }
2079       } else {
2080         // For reasons which are not recorded per-bytecode, we simply
2081         // force recompiles unconditionally.
2082         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2083         make_not_entrant = true;
2084       }
2085 
2086       // Go back to the compiler if there are too many traps in this method.
2087       if (this_trap_count >= per_method_trap_limit(reason)) {
2088         // If there are too many traps in this method, force a recompile.
2089         // This will allow the compiler to see the limit overflow, and
2090         // take corrective action, if possible.
2091         // (This condition is an unlikely backstop only, because the
2092         // PerBytecodeTrapLimit is more likely to take effect first,
2093         // if it is applicable.)
2094         make_not_entrant = true;
2095       }
2096 
2097       // Here's more hysteresis:  If there has been a recompile at
2098       // this trap point already, run the method in the interpreter
2099       // for a while to exercise it more thoroughly.
2100       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2101         reprofile = true;
2102       }
2103     }
2104 
2105     // Take requested actions on the method:
2106 
2107     // Recompile
2108     if (make_not_entrant) {
2109       if (!nm->make_not_entrant()) {
2110         return; // the call did not change nmethod's state
2111       }
2112 
2113       if (pdata != NULL) {
2114         // Record the recompilation event, if any.
2115         int tstate0 = pdata->trap_state();
2116         int tstate1 = trap_state_set_recompiled(tstate0, true);
2117         if (tstate1 != tstate0)
2118           pdata->set_trap_state(tstate1);
2119       }
2120 
2121 #if INCLUDE_RTM_OPT
2122       // Restart collecting RTM locking abort statistic if the method
2123       // is recompiled for a reason other than RTM state change.
2124       // Assume that in new recompiled code the statistic could be different,
2125       // for example, due to different inlining.
2126       if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
2127           UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {
2128         trap_mdo->atomic_set_rtm_state(ProfileRTM);
2129       }
2130 #endif
2131       // For code aging we count traps separately here, using make_not_entrant()
2132       // as a guard against simultaneous deopts in multiple threads.
2133       if (reason == Reason_tenured && trap_mdo != NULL) {
2134         trap_mdo->inc_tenure_traps();
2135       }
2136     }
2137 
2138     if (inc_recompile_count) {
2139       trap_mdo->inc_overflow_recompile_count();
2140       if ((uint)trap_mdo->overflow_recompile_count() >
2141           (uint)PerBytecodeRecompilationCutoff) {
2142         // Give up on the method containing the bad BCI.
2143         if (trap_method() == nm->method()) {
2144           make_not_compilable = true;
2145         } else {
2146           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2147           // But give grace to the enclosing nm->method().
2148         }
2149       }
2150     }
2151 
2152     // Reprofile
2153     if (reprofile) {
2154       CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
2155     }
2156 
2157     // Give up compiling
2158     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2159       assert(make_not_entrant, "consistent");
2160       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2161     }
2162 
2163   } // Free marked resources
2164 
2165 }
2166 JRT_END
2167 
2168 ProfileData*
2169 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2170                                          int trap_bci,
2171                                          Deoptimization::DeoptReason reason,
2172                                          bool update_total_trap_count,
2173 #if INCLUDE_JVMCI
2174                                          bool is_osr,
2175 #endif
2176                                          Method* compiled_method,
2177                                          //outputs:
2178                                          uint& ret_this_trap_count,
2179                                          bool& ret_maybe_prior_trap,
2180                                          bool& ret_maybe_prior_recompile) {
2181   bool maybe_prior_trap = false;
2182   bool maybe_prior_recompile = false;
2183   uint this_trap_count = 0;
2184   if (update_total_trap_count) {
2185     uint idx = reason;
2186 #if INCLUDE_JVMCI
2187     if (is_osr) {
2188       idx += Reason_LIMIT;
2189     }
2190 #endif
2191     uint prior_trap_count = trap_mdo->trap_count(idx);
2192     this_trap_count  = trap_mdo->inc_trap_count(idx);
2193 
2194     // If the runtime cannot find a place to store trap history,
2195     // it is estimated based on the general condition of the method.
2196     // If the method has ever been recompiled, or has ever incurred
2197     // a trap with the present reason , then this BCI is assumed
2198     // (pessimistically) to be the culprit.
2199     maybe_prior_trap      = (prior_trap_count != 0);
2200     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2201   }
2202   ProfileData* pdata = NULL;
2203 
2204 
2205   // For reasons which are recorded per bytecode, we check per-BCI data.
2206   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2207   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2208   if (per_bc_reason != Reason_none) {
2209     // Find the profile data for this BCI.  If there isn't one,
2210     // try to allocate one from the MDO's set of spares.
2211     // This will let us detect a repeated trap at this point.
2212     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
2213 
2214     if (pdata != NULL) {
2215       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2216         if (LogCompilation && xtty != NULL) {
2217           ttyLocker ttyl;
2218           // no more room for speculative traps in this MDO
2219           xtty->elem("speculative_traps_oom");
2220         }
2221       }
2222       // Query the trap state of this profile datum.
2223       int tstate0 = pdata->trap_state();
2224       if (!trap_state_has_reason(tstate0, per_bc_reason))
2225         maybe_prior_trap = false;
2226       if (!trap_state_is_recompiled(tstate0))
2227         maybe_prior_recompile = false;
2228 
2229       // Update the trap state of this profile datum.
2230       int tstate1 = tstate0;
2231       // Record the reason.
2232       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2233       // Store the updated state on the MDO, for next time.
2234       if (tstate1 != tstate0)
2235         pdata->set_trap_state(tstate1);
2236     } else {
2237       if (LogCompilation && xtty != NULL) {
2238         ttyLocker ttyl;
2239         // Missing MDP?  Leave a small complaint in the log.
2240         xtty->elem("missing_mdp bci='%d'", trap_bci);
2241       }
2242     }
2243   }
2244 
2245   // Return results:
2246   ret_this_trap_count = this_trap_count;
2247   ret_maybe_prior_trap = maybe_prior_trap;
2248   ret_maybe_prior_recompile = maybe_prior_recompile;
2249   return pdata;
2250 }
2251 
2252 void
2253 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2254   ResourceMark rm;
2255   // Ignored outputs:
2256   uint ignore_this_trap_count;
2257   bool ignore_maybe_prior_trap;
2258   bool ignore_maybe_prior_recompile;
2259   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2260   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2261   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2262   query_update_method_data(trap_mdo, trap_bci,
2263                            (DeoptReason)reason,
2264                            update_total_counts,
2265 #if INCLUDE_JVMCI
2266                            false,
2267 #endif
2268                            NULL,
2269                            ignore_this_trap_count,
2270                            ignore_maybe_prior_trap,
2271                            ignore_maybe_prior_recompile);
2272 }
2273 
2274 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) {
2275   if (TraceDeoptimization) {
2276     tty->print("Uncommon trap ");
2277   }
2278   // Still in Java no safepoints
2279   {
2280     // This enters VM and may safepoint
2281     uncommon_trap_inner(thread, trap_request);
2282   }
2283   return fetch_unroll_info_helper(thread, exec_mode);
2284 }
2285 
2286 // Local derived constants.
2287 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2288 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2289 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2290 
2291 //---------------------------trap_state_reason---------------------------------
2292 Deoptimization::DeoptReason
2293 Deoptimization::trap_state_reason(int trap_state) {
2294   // This assert provides the link between the width of DataLayout::trap_bits
2295   // and the encoding of "recorded" reasons.  It ensures there are enough
2296   // bits to store all needed reasons in the per-BCI MDO profile.
2297   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2298   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2299   trap_state -= recompile_bit;
2300   if (trap_state == DS_REASON_MASK) {
2301     return Reason_many;
2302   } else {
2303     assert((int)Reason_none == 0, "state=0 => Reason_none");
2304     return (DeoptReason)trap_state;
2305   }
2306 }
2307 //-------------------------trap_state_has_reason-------------------------------
2308 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2309   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2310   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2311   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2312   trap_state -= recompile_bit;
2313   if (trap_state == DS_REASON_MASK) {
2314     return -1;  // true, unspecifically (bottom of state lattice)
2315   } else if (trap_state == reason) {
2316     return 1;   // true, definitely
2317   } else if (trap_state == 0) {
2318     return 0;   // false, definitely (top of state lattice)
2319   } else {
2320     return 0;   // false, definitely
2321   }
2322 }
2323 //-------------------------trap_state_add_reason-------------------------------
2324 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2325   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2326   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2327   trap_state -= recompile_bit;
2328   if (trap_state == DS_REASON_MASK) {
2329     return trap_state + recompile_bit;     // already at state lattice bottom
2330   } else if (trap_state == reason) {
2331     return trap_state + recompile_bit;     // the condition is already true
2332   } else if (trap_state == 0) {
2333     return reason + recompile_bit;          // no condition has yet been true
2334   } else {
2335     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2336   }
2337 }
2338 //-----------------------trap_state_is_recompiled------------------------------
2339 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2340   return (trap_state & DS_RECOMPILE_BIT) != 0;
2341 }
2342 //-----------------------trap_state_set_recompiled-----------------------------
2343 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2344   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2345   else    return trap_state & ~DS_RECOMPILE_BIT;
2346 }
2347 //---------------------------format_trap_state---------------------------------
2348 // This is used for debugging and diagnostics, including LogFile output.
2349 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2350                                               int trap_state) {
2351   assert(buflen > 0, "sanity");
2352   DeoptReason reason      = trap_state_reason(trap_state);
2353   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2354   // Re-encode the state from its decoded components.
2355   int decoded_state = 0;
2356   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2357     decoded_state = trap_state_add_reason(decoded_state, reason);
2358   if (recomp_flag)
2359     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2360   // If the state re-encodes properly, format it symbolically.
2361   // Because this routine is used for debugging and diagnostics,
2362   // be robust even if the state is a strange value.
2363   size_t len;
2364   if (decoded_state != trap_state) {
2365     // Random buggy state that doesn't decode??
2366     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2367   } else {
2368     len = jio_snprintf(buf, buflen, "%s%s",
2369                        trap_reason_name(reason),
2370                        recomp_flag ? " recompiled" : "");
2371   }
2372   return buf;
2373 }
2374 
2375 
2376 //--------------------------------statics--------------------------------------
2377 const char* Deoptimization::_trap_reason_name[] = {
2378   // Note:  Keep this in sync. with enum DeoptReason.
2379   "none",
2380   "null_check",
2381   "null_assert" JVMCI_ONLY("_or_unreached0"),
2382   "range_check",
2383   "class_check",
2384   "array_check",
2385   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2386   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2387   "profile_predicate",
2388   "unloaded",
2389   "uninitialized",
2390   "initialized",
2391   "unreached",
2392   "unhandled",
2393   "constraint",
2394   "div0_check",
2395   "age",
2396   "predicate",
2397   "loop_limit_check",
2398   "speculate_class_check",
2399   "speculate_null_check",
2400   "speculate_null_assert",
2401   "rtm_state_change",
2402   "unstable_if",
2403   "unstable_fused_if",
2404 #if INCLUDE_JVMCI
2405   "aliasing",
2406   "transfer_to_interpreter",
2407   "not_compiled_exception_handler",
2408   "unresolved",
2409   "jsr_mismatch",
2410 #endif
2411   "tenured"
2412 };
2413 const char* Deoptimization::_trap_action_name[] = {
2414   // Note:  Keep this in sync. with enum DeoptAction.
2415   "none",
2416   "maybe_recompile",
2417   "reinterpret",
2418   "make_not_entrant",
2419   "make_not_compilable"
2420 };
2421 
2422 const char* Deoptimization::trap_reason_name(int reason) {
2423   // Check that every reason has a name
2424   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2425 
2426   if (reason == Reason_many)  return "many";
2427   if ((uint)reason < Reason_LIMIT)
2428     return _trap_reason_name[reason];
2429   static char buf[20];
2430   sprintf(buf, "reason%d", reason);
2431   return buf;
2432 }
2433 const char* Deoptimization::trap_action_name(int action) {
2434   // Check that every action has a name
2435   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2436 
2437   if ((uint)action < Action_LIMIT)
2438     return _trap_action_name[action];
2439   static char buf[20];
2440   sprintf(buf, "action%d", action);
2441   return buf;
2442 }
2443 
2444 // This is used for debugging and diagnostics, including LogFile output.
2445 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2446                                                 int trap_request) {
2447   jint unloaded_class_index = trap_request_index(trap_request);
2448   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2449   const char* action = trap_action_name(trap_request_action(trap_request));
2450 #if INCLUDE_JVMCI
2451   int debug_id = trap_request_debug_id(trap_request);
2452 #endif
2453   size_t len;
2454   if (unloaded_class_index < 0) {
2455     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2456                        reason, action
2457 #if INCLUDE_JVMCI
2458                        ,debug_id
2459 #endif
2460                        );
2461   } else {
2462     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2463                        reason, action, unloaded_class_index
2464 #if INCLUDE_JVMCI
2465                        ,debug_id
2466 #endif
2467                        );
2468   }
2469   return buf;
2470 }
2471 
2472 juint Deoptimization::_deoptimization_hist
2473         [Deoptimization::Reason_LIMIT]
2474     [1 + Deoptimization::Action_LIMIT]
2475         [Deoptimization::BC_CASE_LIMIT]
2476   = {0};
2477 
2478 enum {
2479   LSB_BITS = 8,
2480   LSB_MASK = right_n_bits(LSB_BITS)
2481 };
2482 
2483 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2484                                        Bytecodes::Code bc) {
2485   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2486   assert(action >= 0 && action < Action_LIMIT, "oob");
2487   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2488   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2489   juint* cases = _deoptimization_hist[reason][1+action];
2490   juint* bc_counter_addr = NULL;
2491   juint  bc_counter      = 0;
2492   // Look for an unused counter, or an exact match to this BC.
2493   if (bc != Bytecodes::_illegal) {
2494     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2495       juint* counter_addr = &cases[bc_case];
2496       juint  counter = *counter_addr;
2497       if ((counter == 0 && bc_counter_addr == NULL)
2498           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2499         // this counter is either free or is already devoted to this BC
2500         bc_counter_addr = counter_addr;
2501         bc_counter = counter | bc;
2502       }
2503     }
2504   }
2505   if (bc_counter_addr == NULL) {
2506     // Overflow, or no given bytecode.
2507     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2508     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2509   }
2510   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2511 }
2512 
2513 jint Deoptimization::total_deoptimization_count() {
2514   return _deoptimization_hist[Reason_none][0][0];
2515 }
2516 
2517 void Deoptimization::print_statistics() {
2518   juint total = total_deoptimization_count();
2519   juint account = total;
2520   if (total != 0) {
2521     ttyLocker ttyl;
2522     if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
2523     tty->print_cr("Deoptimization traps recorded:");
2524     #define PRINT_STAT_LINE(name, r) \
2525       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2526     PRINT_STAT_LINE("total", total);
2527     // For each non-zero entry in the histogram, print the reason,
2528     // the action, and (if specifically known) the type of bytecode.
2529     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2530       for (int action = 0; action < Action_LIMIT; action++) {
2531         juint* cases = _deoptimization_hist[reason][1+action];
2532         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2533           juint counter = cases[bc_case];
2534           if (counter != 0) {
2535             char name[1*K];
2536             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2537             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2538               bc = Bytecodes::_illegal;
2539             sprintf(name, "%s/%s/%s",
2540                     trap_reason_name(reason),
2541                     trap_action_name(action),
2542                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2543             juint r = counter >> LSB_BITS;
2544             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2545             account -= r;
2546           }
2547         }
2548       }
2549     }
2550     if (account != 0) {
2551       PRINT_STAT_LINE("unaccounted", account);
2552     }
2553     #undef PRINT_STAT_LINE
2554     if (xtty != NULL)  xtty->tail("statistics");
2555   }
2556 }
2557 #else // COMPILER2_OR_JVMCI
2558 
2559 
2560 // Stubs for C1 only system.
2561 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2562   return false;
2563 }
2564 
2565 const char* Deoptimization::trap_reason_name(int reason) {
2566   return "unknown";
2567 }
2568 
2569 void Deoptimization::print_statistics() {
2570   // no output
2571 }
2572 
2573 void
2574 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2575   // no udpate
2576 }
2577 
2578 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2579   return 0;
2580 }
2581 
2582 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2583                                        Bytecodes::Code bc) {
2584   // no update
2585 }
2586 
2587 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2588                                               int trap_state) {
2589   jio_snprintf(buf, buflen, "#%d", trap_state);
2590   return buf;
2591 }
2592 
2593 #endif // COMPILER2_OR_JVMCI