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