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