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