src/share/vm/runtime/deoptimization.cpp

Sat, 07 Nov 2020 10:30:02 +0800

author
aoqi
date
Sat, 07 Nov 2020 10:30:02 +0800
changeset 10026
8c95980d0b66
parent 9448
73d689add964
permissions
-rw-r--r--

Added tag mips-jdk8u275-b01 for changeset d3b4d62f391f

     1 /*
     2  * Copyright (c) 1997, 2016, 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  */
    25 /*
    26  * This file has been modified by Loongson Technology in 2015. These
    27  * modifications are Copyright (c) 2015 Loongson Technology, and are made
    28  * available on the same license terms set forth above.
    29  */
    31 #include "precompiled.hpp"
    32 #include "classfile/systemDictionary.hpp"
    33 #include "code/debugInfoRec.hpp"
    34 #include "code/nmethod.hpp"
    35 #include "code/pcDesc.hpp"
    36 #include "code/scopeDesc.hpp"
    37 #include "interpreter/bytecode.hpp"
    38 #include "interpreter/interpreter.hpp"
    39 #include "interpreter/oopMapCache.hpp"
    40 #include "memory/allocation.inline.hpp"
    41 #include "memory/oopFactory.hpp"
    42 #include "memory/resourceArea.hpp"
    43 #include "oops/method.hpp"
    44 #include "oops/oop.inline.hpp"
    45 #include "prims/jvmtiThreadState.hpp"
    46 #include "runtime/biasedLocking.hpp"
    47 #include "runtime/compilationPolicy.hpp"
    48 #include "runtime/deoptimization.hpp"
    49 #include "runtime/interfaceSupport.hpp"
    50 #include "runtime/sharedRuntime.hpp"
    51 #include "runtime/signature.hpp"
    52 #include "runtime/stubRoutines.hpp"
    53 #include "runtime/thread.hpp"
    54 #include "runtime/vframe.hpp"
    55 #include "runtime/vframeArray.hpp"
    56 #include "runtime/vframe_hp.hpp"
    57 #include "utilities/events.hpp"
    58 #include "utilities/xmlstream.hpp"
    59 #ifdef TARGET_ARCH_x86
    60 # include "vmreg_x86.inline.hpp"
    61 #endif
    62 #ifdef TARGET_ARCH_sparc
    63 # include "vmreg_sparc.inline.hpp"
    64 #endif
    65 #ifdef TARGET_ARCH_zero
    66 # include "vmreg_zero.inline.hpp"
    67 #endif
    68 #ifdef TARGET_ARCH_arm
    69 # include "vmreg_arm.inline.hpp"
    70 #endif
    71 #ifdef TARGET_ARCH_ppc
    72 # include "vmreg_ppc.inline.hpp"
    73 #endif
    74 #ifdef TARGET_ARCH_mips
    75 # include "vmreg_mips.inline.hpp"
    76 #endif
    77 #ifdef COMPILER2
    78 #if defined AD_MD_HPP
    79 # include AD_MD_HPP
    80 #elif defined TARGET_ARCH_MODEL_x86_32
    81 # include "adfiles/ad_x86_32.hpp"
    82 #elif defined TARGET_ARCH_MODEL_x86_64
    83 # include "adfiles/ad_x86_64.hpp"
    84 #elif defined TARGET_ARCH_MODEL_sparc
    85 # include "adfiles/ad_sparc.hpp"
    86 #elif defined TARGET_ARCH_MODEL_zero
    87 # include "adfiles/ad_zero.hpp"
    88 #elif defined TARGET_ARCH_MODEL_ppc_64
    89 # include "adfiles/ad_ppc_64.hpp"
    90 #endif
    91 #ifdef TARGET_ARCH_MODEL_mips_64
    92 # include "adfiles/ad_mips_64.hpp"
    93 #endif
    94 #endif // COMPILER2
    96 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    98 bool DeoptimizationMarker::_is_active = false;
   100 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
   101                                          int  caller_adjustment,
   102                                          int  caller_actual_parameters,
   103                                          int  number_of_frames,
   104                                          intptr_t* frame_sizes,
   105                                          address* frame_pcs,
   106                                          BasicType return_type) {
   107   _size_of_deoptimized_frame = size_of_deoptimized_frame;
   108   _caller_adjustment         = caller_adjustment;
   109   _caller_actual_parameters  = caller_actual_parameters;
   110   _number_of_frames          = number_of_frames;
   111   _frame_sizes               = frame_sizes;
   112   _frame_pcs                 = frame_pcs;
   113   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
   114   _return_type               = return_type;
   115   _initial_info              = 0;
   116   // PD (x86 only)
   117   _counter_temp              = 0;
   118   _unpack_kind               = 0;
   119   _sender_sp_temp            = 0;
   121   _total_frame_sizes         = size_of_frames();
   122 }
   125 Deoptimization::UnrollBlock::~UnrollBlock() {
   126   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
   127   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
   128   FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
   129 }
   132 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
   133   assert(register_number < RegisterMap::reg_count, "checking register number");
   134   return &_register_block[register_number * 2];
   135 }
   139 int Deoptimization::UnrollBlock::size_of_frames() const {
   140   // Acount first for the adjustment of the initial frame
   141   int result = _caller_adjustment;
   142   for (int index = 0; index < number_of_frames(); index++) {
   143     result += frame_sizes()[index];
   144   }
   145   return result;
   146 }
   149 void Deoptimization::UnrollBlock::print() {
   150   ttyLocker ttyl;
   151   tty->print_cr("UnrollBlock");
   152   tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
   153   tty->print(   "  frame_sizes: ");
   154   for (int index = 0; index < number_of_frames(); index++) {
   155     tty->print("%d ", frame_sizes()[index]);
   156   }
   157   tty->cr();
   158 }
   161 // In order to make fetch_unroll_info work properly with escape
   162 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
   163 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
   164 // of previously eliminated objects occurs in realloc_objects, which is
   165 // called from the method fetch_unroll_info_helper below.
   166 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))
   167   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
   168   // but makes the entry a little slower. There is however a little dance we have to
   169   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
   171   // fetch_unroll_info() is called at the beginning of the deoptimization
   172   // handler. Note this fact before we start generating temporary frames
   173   // that can confuse an asynchronous stack walker. This counter is
   174   // decremented at the end of unpack_frames().
   175   thread->inc_in_deopt_handler();
   177   return fetch_unroll_info_helper(thread);
   178 JRT_END
   181 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
   182 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {
   184   // Note: there is a safepoint safety issue here. No matter whether we enter
   185   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
   186   // the vframeArray is created.
   187   //
   189   // Allocate our special deoptimization ResourceMark
   190   DeoptResourceMark* dmark = new DeoptResourceMark(thread);
   191   assert(thread->deopt_mark() == NULL, "Pending deopt!");
   192   thread->set_deopt_mark(dmark);
   194   frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
   195   RegisterMap map(thread, true);
   196   RegisterMap dummy_map(thread, false);
   197   // Now get the deoptee with a valid map
   198   frame deoptee = stub_frame.sender(&map);
   199   // Set the deoptee nmethod
   200   assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
   201   thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
   203   if (VerifyStack) {
   204     thread->validate_frame_layout();
   205   }
   207   // Create a growable array of VFrames where each VFrame represents an inlined
   208   // Java frame.  This storage is allocated with the usual system arena.
   209   assert(deoptee.is_compiled_frame(), "Wrong frame type");
   210   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
   211   vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
   212   while (!vf->is_top()) {
   213     assert(vf->is_compiled_frame(), "Wrong frame type");
   214     chunk->push(compiledVFrame::cast(vf));
   215     vf = vf->sender();
   216   }
   217   assert(vf->is_compiled_frame(), "Wrong frame type");
   218   chunk->push(compiledVFrame::cast(vf));
   220   bool realloc_failures = false;
   222 #ifdef COMPILER2
   223   // Reallocate the non-escaping objects and restore their fields. Then
   224   // relock objects if synchronization on them was eliminated.
   225   if (DoEscapeAnalysis || EliminateNestedLocks) {
   226     if (EliminateAllocations) {
   227       assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
   228       GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
   230       // The flag return_oop() indicates call sites which return oop
   231       // in compiled code. Such sites include java method calls,
   232       // runtime calls (for example, used to allocate new objects/arrays
   233       // on slow code path) and any other calls generated in compiled code.
   234       // It is not guaranteed that we can get such information here only
   235       // by analyzing bytecode in deoptimized frames. This is why this flag
   236       // is set during method compilation (see Compile::Process_OopMap_Node()).
   237       // If the previous frame was popped, we don't have a result.
   238       bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution();
   239       Handle return_value;
   240       if (save_oop_result) {
   241         // Reallocation may trigger GC. If deoptimization happened on return from
   242         // call which returns oop we need to save it since it is not in oopmap.
   243         oop result = deoptee.saved_oop_result(&map);
   244         assert(result == NULL || result->is_oop(), "must be oop");
   245         return_value = Handle(thread, result);
   246         assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
   247         if (TraceDeoptimization) {
   248           ttyLocker ttyl;
   249           tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);
   250         }
   251       }
   252       if (objects != NULL) {
   253         JRT_BLOCK
   254           realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD);
   255         JRT_END
   256         reassign_fields(&deoptee, &map, objects, realloc_failures);
   257 #ifndef PRODUCT
   258         if (TraceDeoptimization) {
   259           ttyLocker ttyl;
   260           tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
   261           print_objects(objects, realloc_failures);
   262         }
   263 #endif
   264       }
   265       if (save_oop_result) {
   266         // Restore result.
   267         deoptee.set_saved_oop_result(&map, return_value());
   268       }
   269     }
   270     if (EliminateLocks) {
   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 (TraceDeoptimization) {
   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, 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", (void *)mi->owner());
   295                 }
   296               }
   297             }
   298           }
   299 #endif
   300         }
   301       }
   302     }
   303   }
   304 #endif // COMPILER2
   305   // Ensure that no safepoint is taken after pointers have been stored
   306   // in fields of rematerialized objects.  If a safepoint occurs from here on
   307   // out the java state residing in the vframeArray will be missed.
   308   No_Safepoint_Verifier no_safepoint;
   310   vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
   311 #ifdef COMPILER2
   312   if (realloc_failures) {
   313     pop_frames_failed_reallocs(thread, array);
   314   }
   315 #endif
   317   assert(thread->vframe_array_head() == NULL, "Pending deopt!");
   318   thread->set_vframe_array_head(array);
   320   // Now that the vframeArray has been created if we have any deferred local writes
   321   // added by jvmti then we can free up that structure as the data is now in the
   322   // vframeArray
   324   if (thread->deferred_locals() != NULL) {
   325     GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
   326     int i = 0;
   327     do {
   328       // Because of inlining we could have multiple vframes for a single frame
   329       // and several of the vframes could have deferred writes. Find them all.
   330       if (list->at(i)->id() == array->original().id()) {
   331         jvmtiDeferredLocalVariableSet* dlv = list->at(i);
   332         list->remove_at(i);
   333         // individual jvmtiDeferredLocalVariableSet are CHeapObj's
   334         delete dlv;
   335       } else {
   336         i++;
   337       }
   338     } while ( i < list->length() );
   339     if (list->length() == 0) {
   340       thread->set_deferred_locals(NULL);
   341       // free the list and elements back to C heap.
   342       delete list;
   343     }
   345   }
   347 #ifndef SHARK
   348   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
   349   CodeBlob* cb = stub_frame.cb();
   350   // Verify we have the right vframeArray
   351   assert(cb->frame_size() >= 0, "Unexpected frame size");
   352   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
   354   // If the deopt call site is a MethodHandle invoke call site we have
   355   // to adjust the unpack_sp.
   356   nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
   357   if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
   358     unpack_sp = deoptee.unextended_sp();
   360 #ifdef ASSERT
   361   assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");
   362 #endif
   363 #else
   364   intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
   365 #endif // !SHARK
   367   // This is a guarantee instead of an assert because if vframe doesn't match
   368   // we will unpack the wrong deoptimized frame and wind up in strange places
   369   // where it will be very difficult to figure out what went wrong. Better
   370   // to die an early death here than some very obscure death later when the
   371   // trail is cold.
   372   // Note: on ia64 this guarantee can be fooled by frames with no memory stack
   373   // in that it will fail to detect a problem when there is one. This needs
   374   // more work in tiger timeframe.
   375   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
   377   int number_of_frames = array->frames();
   379   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
   380   // virtual activation, which is the reverse of the elements in the vframes array.
   381   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
   382   // +1 because we always have an interpreter return address for the final slot.
   383   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
   384   int popframe_extra_args = 0;
   385   // Create an interpreter return address for the stub to use as its return
   386   // address so the skeletal frames are perfectly walkable
   387   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
   389   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
   390   // activation be put back on the expression stack of the caller for reexecution
   391   if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
   392     popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
   393   }
   395   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
   396   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
   397   // than simply use array->sender.pc(). This requires us to walk the current set of frames
   398   //
   399   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
   400   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
   402   // It's possible that the number of paramters at the call site is
   403   // different than number of arguments in the callee when method
   404   // handles are used.  If the caller is interpreted get the real
   405   // value so that the proper amount of space can be added to it's
   406   // frame.
   407   bool caller_was_method_handle = false;
   408   if (deopt_sender.is_interpreted_frame()) {
   409     methodHandle method = deopt_sender.interpreter_frame_method();
   410     Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
   411     if (cur.is_invokedynamic() || cur.is_invokehandle()) {
   412       // Method handle invokes may involve fairly arbitrary chains of
   413       // calls so it's impossible to know how much actual space the
   414       // caller has for locals.
   415       caller_was_method_handle = true;
   416     }
   417   }
   419   //
   420   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
   421   // frame_sizes/frame_pcs[1] next oldest frame (int)
   422   // frame_sizes/frame_pcs[n] youngest frame (int)
   423   //
   424   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
   425   // owns the space for the return address to it's caller).  Confusing ain't it.
   426   //
   427   // The vframe array can address vframes with indices running from
   428   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
   429   // When we create the skeletal frames we need the oldest frame to be in the zero slot
   430   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
   431   // so things look a little strange in this loop.
   432   //
   433   int callee_parameters = 0;
   434   int callee_locals = 0;
   435   for (int index = 0; index < array->frames(); index++ ) {
   436     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
   437     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
   438     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
   439     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
   440                                                                                                     callee_locals,
   441                                                                                                     index == 0,
   442                                                                                                     popframe_extra_args);
   443     // This pc doesn't have to be perfect just good enough to identify the frame
   444     // as interpreted so the skeleton frame will be walkable
   445     // The correct pc will be set when the skeleton frame is completely filled out
   446     // The final pc we store in the loop is wrong and will be overwritten below
   447     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
   449     callee_parameters = array->element(index)->method()->size_of_parameters();
   450     callee_locals = array->element(index)->method()->max_locals();
   451     popframe_extra_args = 0;
   452   }
   454   // Compute whether the root vframe returns a float or double value.
   455   BasicType return_type;
   456   {
   457     HandleMark hm;
   458     methodHandle method(thread, array->element(0)->method());
   459     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
   460     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
   461   }
   463   // Compute information for handling adapters and adjusting the frame size of the caller.
   464   int caller_adjustment = 0;
   466   // Compute the amount the oldest interpreter frame will have to adjust
   467   // its caller's stack by. If the caller is a compiled frame then
   468   // we pretend that the callee has no parameters so that the
   469   // extension counts for the full amount of locals and not just
   470   // locals-parms. This is because without a c2i adapter the parm
   471   // area as created by the compiled frame will not be usable by
   472   // the interpreter. (Depending on the calling convention there
   473   // may not even be enough space).
   475   // QQQ I'd rather see this pushed down into last_frame_adjust
   476   // and have it take the sender (aka caller).
   478   if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
   479     caller_adjustment = last_frame_adjust(0, callee_locals);
   480   } else if (callee_locals > callee_parameters) {
   481     // The caller frame may need extending to accommodate
   482     // non-parameter locals of the first unpacked interpreted frame.
   483     // Compute that adjustment.
   484     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
   485   }
   487   // If the sender is deoptimized the we must retrieve the address of the handler
   488   // since the frame will "magically" show the original pc before the deopt
   489   // and we'd undo the deopt.
   491   frame_pcs[0] = deopt_sender.raw_pc();
   493 #ifndef SHARK
   494   assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
   495 #endif // SHARK
   497   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
   498                                       caller_adjustment * BytesPerWord,
   499                                       caller_was_method_handle ? 0 : callee_parameters,
   500                                       number_of_frames,
   501                                       frame_sizes,
   502                                       frame_pcs,
   503                                       return_type);
   504   // On some platforms, we need a way to pass some platform dependent
   505   // information to the unpacking code so the skeletal frames come out
   506   // correct (initial fp value, unextended sp, ...)
   507   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
   509   if (array->frames() > 1) {
   510     if (VerifyStack && TraceDeoptimization) {
   511       ttyLocker ttyl;
   512       tty->print_cr("Deoptimizing method containing inlining");
   513     }
   514   }
   516   array->set_unroll_block(info);
   517   return info;
   518 }
   520 // Called to cleanup deoptimization data structures in normal case
   521 // after unpacking to stack and when stack overflow error occurs
   522 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
   523                                         vframeArray *array) {
   525   // Get array if coming from exception
   526   if (array == NULL) {
   527     array = thread->vframe_array_head();
   528   }
   529   thread->set_vframe_array_head(NULL);
   531   // Free the previous UnrollBlock
   532   vframeArray* old_array = thread->vframe_array_last();
   533   thread->set_vframe_array_last(array);
   535   if (old_array != NULL) {
   536     UnrollBlock* old_info = old_array->unroll_block();
   537     old_array->set_unroll_block(NULL);
   538     delete old_info;
   539     delete old_array;
   540   }
   542   // Deallocate any resource creating in this routine and any ResourceObjs allocated
   543   // inside the vframeArray (StackValueCollections)
   545   delete thread->deopt_mark();
   546   thread->set_deopt_mark(NULL);
   547   thread->set_deopt_nmethod(NULL);
   550   if (JvmtiExport::can_pop_frame()) {
   551 #ifndef CC_INTERP
   552     // Regardless of whether we entered this routine with the pending
   553     // popframe condition bit set, we should always clear it now
   554     thread->clear_popframe_condition();
   555 #else
   556     // C++ interpeter will clear has_pending_popframe when it enters
   557     // with method_resume. For deopt_resume2 we clear it now.
   558     if (thread->popframe_forcing_deopt_reexecution())
   559         thread->clear_popframe_condition();
   560 #endif /* CC_INTERP */
   561   }
   563   // unpack_frames() is called at the end of the deoptimization handler
   564   // and (in C2) at the end of the uncommon trap handler. Note this fact
   565   // so that an asynchronous stack walker can work again. This counter is
   566   // incremented at the beginning of fetch_unroll_info() and (in C2) at
   567   // the beginning of uncommon_trap().
   568   thread->dec_in_deopt_handler();
   569 }
   572 // Return BasicType of value being returned
   573 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
   575   // We are already active int he special DeoptResourceMark any ResourceObj's we
   576   // allocate will be freed at the end of the routine.
   578   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
   579   // but makes the entry a little slower. There is however a little dance we have to
   580   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
   581   ResetNoHandleMark rnhm; // No-op in release/product versions
   582   HandleMark hm;
   584   frame stub_frame = thread->last_frame();
   586   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
   587   // must point to the vframeArray for the unpack frame.
   588   vframeArray* array = thread->vframe_array_head();
   590 #ifndef PRODUCT
   591   if (TraceDeoptimization) {
   592     ttyLocker ttyl;
   593     tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
   594   }
   595 #endif
   596   Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
   597               stub_frame.pc(), stub_frame.sp(), exec_mode);
   599   UnrollBlock* info = array->unroll_block();
   601   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
   602   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
   604   BasicType bt = info->return_type();
   606   // If we have an exception pending, claim that the return type is an oop
   607   // so the deopt_blob does not overwrite the exception_oop.
   609   if (exec_mode == Unpack_exception)
   610     bt = T_OBJECT;
   612   // Cleanup thread deopt data
   613   cleanup_deopt_info(thread, array);
   615 #ifndef PRODUCT
   616   if (VerifyStack) {
   617     ResourceMark res_mark;
   619     thread->validate_frame_layout();
   621     // Verify that the just-unpacked frames match the interpreter's
   622     // notions of expression stack and locals
   623     vframeArray* cur_array = thread->vframe_array_last();
   624     RegisterMap rm(thread, false);
   625     rm.set_include_argument_oops(false);
   626     bool is_top_frame = true;
   627     int callee_size_of_parameters = 0;
   628     int callee_max_locals = 0;
   629     for (int i = 0; i < cur_array->frames(); i++) {
   630       vframeArrayElement* el = cur_array->element(i);
   631       frame* iframe = el->iframe();
   632       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
   634       // Get the oop map for this bci
   635       InterpreterOopMap mask;
   636       int cur_invoke_parameter_size = 0;
   637       bool try_next_mask = false;
   638       int next_mask_expression_stack_size = -1;
   639       int top_frame_expression_stack_adjustment = 0;
   640       methodHandle mh(thread, iframe->interpreter_frame_method());
   641       OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
   642       BytecodeStream str(mh);
   643       str.set_start(iframe->interpreter_frame_bci());
   644       int max_bci = mh->code_size();
   645       // Get to the next bytecode if possible
   646       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
   647       // Check to see if we can grab the number of outgoing arguments
   648       // at an uncommon trap for an invoke (where the compiler
   649       // generates debug info before the invoke has executed)
   650       Bytecodes::Code cur_code = str.next();
   651       if (cur_code == Bytecodes::_invokevirtual   ||
   652           cur_code == Bytecodes::_invokespecial   ||
   653           cur_code == Bytecodes::_invokestatic    ||
   654           cur_code == Bytecodes::_invokeinterface ||
   655           cur_code == Bytecodes::_invokedynamic) {
   656         Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
   657         Symbol* signature = invoke.signature();
   658         ArgumentSizeComputer asc(signature);
   659         cur_invoke_parameter_size = asc.size();
   660         if (invoke.has_receiver()) {
   661           // Add in receiver
   662           ++cur_invoke_parameter_size;
   663         }
   664         if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
   665           callee_size_of_parameters++;
   666         }
   667       }
   668       if (str.bci() < max_bci) {
   669         Bytecodes::Code bc = str.next();
   670         if (bc >= 0) {
   671           // The interpreter oop map generator reports results before
   672           // the current bytecode has executed except in the case of
   673           // calls. It seems to be hard to tell whether the compiler
   674           // has emitted debug information matching the "state before"
   675           // a given bytecode or the state after, so we try both
   676           switch (cur_code) {
   677             case Bytecodes::_invokevirtual:
   678             case Bytecodes::_invokespecial:
   679             case Bytecodes::_invokestatic:
   680             case Bytecodes::_invokeinterface:
   681             case Bytecodes::_invokedynamic:
   682             case Bytecodes::_athrow:
   683               break;
   684             default: {
   685               InterpreterOopMap next_mask;
   686               OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
   687               next_mask_expression_stack_size = next_mask.expression_stack_size();
   688               // Need to subtract off the size of the result type of
   689               // the bytecode because this is not described in the
   690               // debug info but returned to the interpreter in the TOS
   691               // caching register
   692               BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
   693               if (bytecode_result_type != T_ILLEGAL) {
   694                 top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
   695               }
   696               assert(top_frame_expression_stack_adjustment >= 0, "");
   697               try_next_mask = true;
   698               break;
   699             }
   700           }
   701         }
   702       }
   704       // Verify stack depth and oops in frame
   705       // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
   706       if (!(
   707             /* SPARC */
   708             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
   709             /* x86 */
   710             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
   711             (try_next_mask &&
   712              (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
   713                                                                     top_frame_expression_stack_adjustment))) ||
   714             (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
   715             (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
   716              (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
   717             )) {
   718         ttyLocker ttyl;
   720         // Print out some information that will help us debug the problem
   721         tty->print_cr("Wrong number of expression stack elements during deoptimization");
   722         tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
   723         tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
   724                       iframe->interpreter_frame_expression_stack_size());
   725         tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
   726         tty->print_cr("  try_next_mask = %d", try_next_mask);
   727         tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
   728         tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
   729         tty->print_cr("  callee_max_locals = %d", callee_max_locals);
   730         tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
   731         tty->print_cr("  exec_mode = %d", exec_mode);
   732         tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
   733         tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
   734         tty->print_cr("  Interpreted frames:");
   735         for (int k = 0; k < cur_array->frames(); k++) {
   736           vframeArrayElement* el = cur_array->element(k);
   737           tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
   738         }
   739         cur_array->print_on_2(tty);
   740         guarantee(false, "wrong number of expression stack elements during deopt");
   741       }
   742       VerifyOopClosure verify;
   743       iframe->oops_interpreted_do(&verify, NULL, &rm, false);
   744       callee_size_of_parameters = mh->size_of_parameters();
   745       callee_max_locals = mh->max_locals();
   746       is_top_frame = false;
   747     }
   748   }
   749 #endif /* !PRODUCT */
   752   return bt;
   753 JRT_END
   756 int Deoptimization::deoptimize_dependents() {
   757   Threads::deoptimized_wrt_marked_nmethods();
   758   return 0;
   759 }
   762 #ifdef COMPILER2
   763 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
   764   Handle pending_exception(thread->pending_exception());
   765   const char* exception_file = thread->exception_file();
   766   int exception_line = thread->exception_line();
   767   thread->clear_pending_exception();
   769   bool failures = false;
   771   for (int i = 0; i < objects->length(); i++) {
   772     assert(objects->at(i)->is_object(), "invalid debug information");
   773     ObjectValue* sv = (ObjectValue*) objects->at(i);
   775     KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
   776     oop obj = NULL;
   778     if (k->oop_is_instance()) {
   779       InstanceKlass* ik = InstanceKlass::cast(k());
   780       obj = ik->allocate_instance(THREAD);
   781     } else if (k->oop_is_typeArray()) {
   782       TypeArrayKlass* ak = TypeArrayKlass::cast(k());
   783       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
   784       int len = sv->field_size() / type2size[ak->element_type()];
   785       obj = ak->allocate(len, THREAD);
   786     } else if (k->oop_is_objArray()) {
   787       ObjArrayKlass* ak = ObjArrayKlass::cast(k());
   788       obj = ak->allocate(sv->field_size(), THREAD);
   789     }
   791     if (obj == NULL) {
   792       failures = true;
   793     }
   795     assert(sv->value().is_null(), "redundant reallocation");
   796     assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
   797     CLEAR_PENDING_EXCEPTION;
   798     sv->set_value(obj);
   799   }
   801   if (failures) {
   802     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
   803   } else if (pending_exception.not_null()) {
   804     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
   805   }
   807   return failures;
   808 }
   810 // This assumes that the fields are stored in ObjectValue in the same order
   811 // they are yielded by do_nonstatic_fields.
   812 class FieldReassigner: public FieldClosure {
   813   frame* _fr;
   814   RegisterMap* _reg_map;
   815   ObjectValue* _sv;
   816   InstanceKlass* _ik;
   817   oop _obj;
   819   int _i;
   820 public:
   821   FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :
   822     _fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}
   824   int i() const { return _i; }
   827   void do_field(fieldDescriptor* fd) {
   828     intptr_t val;
   829     StackValue* value =
   830       StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));
   831     int offset = fd->offset();
   832     switch (fd->field_type()) {
   833     case T_OBJECT: case T_ARRAY:
   834       assert(value->type() == T_OBJECT, "Agreement.");
   835       _obj->obj_field_put(offset, value->get_obj()());
   836       break;
   838     case T_LONG: case T_DOUBLE: {
   839       assert(value->type() == T_INT, "Agreement.");
   840       StackValue* low =
   841         StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));
   842 #ifdef _LP64
   843       jlong res = (jlong)low->get_int();
   844 #else
   845 #ifdef SPARC
   846       // For SPARC we have to swap high and low words.
   847       jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
   848 #else
   849       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
   850 #endif //SPARC
   851 #endif
   852       _obj->long_field_put(offset, res);
   853       break;
   854     }
   855     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
   856     case T_INT: case T_FLOAT: // 4 bytes.
   857       assert(value->type() == T_INT, "Agreement.");
   858       val = value->get_int();
   859       _obj->int_field_put(offset, (jint)*((jint*)&val));
   860       break;
   862     case T_SHORT:
   863       assert(value->type() == T_INT, "Agreement.");
   864       val = value->get_int();
   865       _obj->short_field_put(offset, (jshort)*((jint*)&val));
   866       break;
   868     case T_CHAR:
   869       assert(value->type() == T_INT, "Agreement.");
   870       val = value->get_int();
   871       _obj->char_field_put(offset, (jchar)*((jint*)&val));
   872       break;
   874     case T_BYTE:
   875       assert(value->type() == T_INT, "Agreement.");
   876       val = value->get_int();
   877       _obj->byte_field_put(offset, (jbyte)*((jint*)&val));
   878       break;
   880     case T_BOOLEAN:
   881       assert(value->type() == T_INT, "Agreement.");
   882       val = value->get_int();
   883       _obj->bool_field_put(offset, (jboolean)*((jint*)&val));
   884       break;
   886     default:
   887       ShouldNotReachHere();
   888     }
   889     _i++;
   890   }
   891 };
   893 // restore elements of an eliminated type array
   894 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
   895   int index = 0;
   896   intptr_t val;
   898   for (int i = 0; i < sv->field_size(); i++) {
   899     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
   900     switch(type) {
   901     case T_LONG: case T_DOUBLE: {
   902       assert(value->type() == T_INT, "Agreement.");
   903       StackValue* low =
   904         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
   905 #ifdef _LP64
   906       jlong res = (jlong)low->get_int();
   907 #else
   908 #ifdef SPARC
   909       // For SPARC we have to swap high and low words.
   910       jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
   911 #else
   912       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
   913 #endif //SPARC
   914 #endif
   915       obj->long_at_put(index, res);
   916       break;
   917     }
   919     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
   920     case T_INT: case T_FLOAT: // 4 bytes.
   921       assert(value->type() == T_INT, "Agreement.");
   922       val = value->get_int();
   923       obj->int_at_put(index, (jint)*((jint*)&val));
   924       break;
   926     case T_SHORT:
   927       assert(value->type() == T_INT, "Agreement.");
   928       val = value->get_int();
   929       obj->short_at_put(index, (jshort)*((jint*)&val));
   930       break;
   932     case T_CHAR:
   933       assert(value->type() == T_INT, "Agreement.");
   934       val = value->get_int();
   935       obj->char_at_put(index, (jchar)*((jint*)&val));
   936       break;
   938     case T_BYTE:
   939       assert(value->type() == T_INT, "Agreement.");
   940       val = value->get_int();
   941       obj->byte_at_put(index, (jbyte)*((jint*)&val));
   942       break;
   944     case T_BOOLEAN:
   945       assert(value->type() == T_INT, "Agreement.");
   946       val = value->get_int();
   947       obj->bool_at_put(index, (jboolean)*((jint*)&val));
   948       break;
   950       default:
   951         ShouldNotReachHere();
   952     }
   953     index++;
   954   }
   955 }
   958 // restore fields of an eliminated object array
   959 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
   960   for (int i = 0; i < sv->field_size(); i++) {
   961     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
   962     assert(value->type() == T_OBJECT, "object element expected");
   963     obj->obj_at_put(i, value->get_obj()());
   964   }
   965 }
   968 // restore fields of all eliminated objects and arrays
   969 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
   970   for (int i = 0; i < objects->length(); i++) {
   971     ObjectValue* sv = (ObjectValue*) objects->at(i);
   972     KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
   973     Handle obj = sv->value();
   974     assert(obj.not_null() || realloc_failures, "reallocation was missed");
   975     if (obj.is_null()) {
   976       continue;
   977     }
   979     if (k->oop_is_instance()) {
   980       InstanceKlass* ik = InstanceKlass::cast(k());
   981       FieldReassigner reassign(fr, reg_map, sv, obj());
   982       ik->do_nonstatic_fields(&reassign);
   983     } else if (k->oop_is_typeArray()) {
   984       TypeArrayKlass* ak = TypeArrayKlass::cast(k());
   985       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
   986     } else if (k->oop_is_objArray()) {
   987       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
   988     }
   989   }
   990 }
   993 // relock objects for which synchronization was eliminated
   994 void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
   995   for (int i = 0; i < monitors->length(); i++) {
   996     MonitorInfo* mon_info = monitors->at(i);
   997     if (mon_info->eliminated()) {
   998       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
   999       if (!mon_info->owner_is_scalar_replaced()) {
  1000         Handle obj = Handle(mon_info->owner());
  1001         markOop mark = obj->mark();
  1002         if (UseBiasedLocking && mark->has_bias_pattern()) {
  1003           // New allocated objects may have the mark set to anonymously biased.
  1004           // Also the deoptimized method may called methods with synchronization
  1005           // where the thread-local object is bias locked to the current thread.
  1006           assert(mark->is_biased_anonymously() ||
  1007                  mark->biased_locker() == thread, "should be locked to current thread");
  1008           // Reset mark word to unbiased prototype.
  1009           markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
  1010           obj->set_mark(unbiased_prototype);
  1012         BasicLock* lock = mon_info->lock();
  1013         ObjectSynchronizer::slow_enter(obj, lock, thread);
  1014         assert(mon_info->owner()->is_locked(), "object must be locked now");
  1021 #ifndef PRODUCT
  1022 // print information about reallocated objects
  1023 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
  1024   fieldDescriptor fd;
  1026   for (int i = 0; i < objects->length(); i++) {
  1027     ObjectValue* sv = (ObjectValue*) objects->at(i);
  1028     KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
  1029     Handle obj = sv->value();
  1031     tty->print("     object <" INTPTR_FORMAT "> of type ", (void *)sv->value()());
  1032     k->print_value();
  1033     assert(obj.not_null() || realloc_failures, "reallocation was missed");
  1034     if (obj.is_null()) {
  1035       tty->print(" allocation failed");
  1036     } else {
  1037       tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
  1039     tty->cr();
  1041     if (Verbose && !obj.is_null()) {
  1042       k->oop_print_on(obj(), tty);
  1046 #endif
  1047 #endif // COMPILER2
  1049 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
  1050   Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());
  1052 #ifndef PRODUCT
  1053   if (TraceDeoptimization) {
  1054     ttyLocker ttyl;
  1055     tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);
  1056     fr.print_on(tty);
  1057     tty->print_cr("     Virtual frames (innermost first):");
  1058     for (int index = 0; index < chunk->length(); index++) {
  1059       compiledVFrame* vf = chunk->at(index);
  1060       tty->print("       %2d - ", index);
  1061       vf->print_value();
  1062       int bci = chunk->at(index)->raw_bci();
  1063       const char* code_name;
  1064       if (bci == SynchronizationEntryBCI) {
  1065         code_name = "sync entry";
  1066       } else {
  1067         Bytecodes::Code code = vf->method()->code_at(bci);
  1068         code_name = Bytecodes::name(code);
  1070       tty->print(" - %s", code_name);
  1071       tty->print_cr(" @ bci %d ", bci);
  1072       if (Verbose) {
  1073         vf->print();
  1074         tty->cr();
  1078 #endif
  1080   // Register map for next frame (used for stack crawl).  We capture
  1081   // the state of the deopt'ing frame's caller.  Thus if we need to
  1082   // stuff a C2I adapter we can properly fill in the callee-save
  1083   // register locations.
  1084   frame caller = fr.sender(reg_map);
  1085   int frame_size = caller.sp() - fr.sp();
  1087   frame sender = caller;
  1089   // Since the Java thread being deoptimized will eventually adjust it's own stack,
  1090   // the vframeArray containing the unpacking information is allocated in the C heap.
  1091   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
  1092   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
  1094   // Compare the vframeArray to the collected vframes
  1095   assert(array->structural_compare(thread, chunk), "just checking");
  1097 #ifndef PRODUCT
  1098   if (TraceDeoptimization) {
  1099     ttyLocker ttyl;
  1100     tty->print_cr("     Created vframeArray " INTPTR_FORMAT, array);
  1102 #endif // PRODUCT
  1104   return array;
  1107 #ifdef COMPILER2
  1108 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
  1109   // Reallocation of some scalar replaced objects failed. Record
  1110   // that we need to pop all the interpreter frames for the
  1111   // deoptimized compiled frame.
  1112   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
  1113   thread->set_frames_to_pop_failed_realloc(array->frames());
  1114   // Unlock all monitors here otherwise the interpreter will see a
  1115   // mix of locked and unlocked monitors (because of failed
  1116   // reallocations of synchronized objects) and be confused.
  1117   for (int i = 0; i < array->frames(); i++) {
  1118     MonitorChunk* monitors = array->element(i)->monitors();
  1119     if (monitors != NULL) {
  1120       for (int j = 0; j < monitors->number_of_monitors(); j++) {
  1121         BasicObjectLock* src = monitors->at(j);
  1122         if (src->obj() != NULL) {
  1123           ObjectSynchronizer::fast_exit(src->obj(), src->lock(), thread);
  1126       array->element(i)->free_monitors(thread);
  1127 #ifdef ASSERT
  1128       array->element(i)->set_removed_monitors();
  1129 #endif
  1133 #endif
  1135 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
  1136   GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
  1137   for (int i = 0; i < monitors->length(); i++) {
  1138     MonitorInfo* mon_info = monitors->at(i);
  1139     if (!mon_info->eliminated() && mon_info->owner() != NULL) {
  1140       objects_to_revoke->append(Handle(mon_info->owner()));
  1146 void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
  1147   if (!UseBiasedLocking) {
  1148     return;
  1151   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
  1153   // Unfortunately we don't have a RegisterMap available in most of
  1154   // the places we want to call this routine so we need to walk the
  1155   // stack again to update the register map.
  1156   if (map == NULL || !map->update_map()) {
  1157     StackFrameStream sfs(thread, true);
  1158     bool found = false;
  1159     while (!found && !sfs.is_done()) {
  1160       frame* cur = sfs.current();
  1161       sfs.next();
  1162       found = cur->id() == fr.id();
  1164     assert(found, "frame to be deoptimized not found on target thread's stack");
  1165     map = sfs.register_map();
  1168   vframe* vf = vframe::new_vframe(&fr, map, thread);
  1169   compiledVFrame* cvf = compiledVFrame::cast(vf);
  1170   // Revoke monitors' biases in all scopes
  1171   while (!cvf->is_top()) {
  1172     collect_monitors(cvf, objects_to_revoke);
  1173     cvf = compiledVFrame::cast(cvf->sender());
  1175   collect_monitors(cvf, objects_to_revoke);
  1177   if (SafepointSynchronize::is_at_safepoint()) {
  1178     BiasedLocking::revoke_at_safepoint(objects_to_revoke);
  1179   } else {
  1180     BiasedLocking::revoke(objects_to_revoke);
  1185 void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
  1186   if (!UseBiasedLocking) {
  1187     return;
  1190   assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
  1191   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
  1192   for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
  1193     if (jt->has_last_Java_frame()) {
  1194       StackFrameStream sfs(jt, true);
  1195       while (!sfs.is_done()) {
  1196         frame* cur = sfs.current();
  1197         if (cb->contains(cur->pc())) {
  1198           vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
  1199           compiledVFrame* cvf = compiledVFrame::cast(vf);
  1200           // Revoke monitors' biases in all scopes
  1201           while (!cvf->is_top()) {
  1202             collect_monitors(cvf, objects_to_revoke);
  1203             cvf = compiledVFrame::cast(cvf->sender());
  1205           collect_monitors(cvf, objects_to_revoke);
  1207         sfs.next();
  1211   BiasedLocking::revoke_at_safepoint(objects_to_revoke);
  1215 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {
  1216   assert(fr.can_be_deoptimized(), "checking frame type");
  1218   gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);
  1220   // Patch the nmethod so that when execution returns to it we will
  1221   // deopt the execution state and return to the interpreter.
  1222   fr.deoptimize(thread);
  1225 void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
  1226   // Deoptimize only if the frame comes from compile code.
  1227   // Do not deoptimize the frame which is already patched
  1228   // during the execution of the loops below.
  1229   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
  1230     return;
  1232   ResourceMark rm;
  1233   DeoptimizationMarker dm;
  1234   if (UseBiasedLocking) {
  1235     revoke_biases_of_monitors(thread, fr, map);
  1237   deoptimize_single_frame(thread, fr);
  1242 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {
  1243   assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
  1244          "can only deoptimize other thread at a safepoint");
  1245   // Compute frame and register map based on thread and sp.
  1246   RegisterMap reg_map(thread, UseBiasedLocking);
  1247   frame fr = thread->last_frame();
  1248   while (fr.id() != id) {
  1249     fr = fr.sender(&reg_map);
  1251   deoptimize(thread, fr, &reg_map);
  1255 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
  1256   if (thread == Thread::current()) {
  1257     Deoptimization::deoptimize_frame_internal(thread, id);
  1258   } else {
  1259     VM_DeoptimizeFrame deopt(thread, id);
  1260     VMThread::execute(&deopt);
  1265 // JVMTI PopFrame support
  1266 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
  1268   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
  1270 JRT_END
  1273 #if defined(COMPILER2) || defined(SHARK)
  1274 void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
  1275   // in case of an unresolved klass entry, load the class.
  1276   if (constant_pool->tag_at(index).is_unresolved_klass()) {
  1277     Klass* tk = constant_pool->klass_at(index, CHECK);
  1278     return;
  1281   if (!constant_pool->tag_at(index).is_symbol()) return;
  1283   Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());
  1284   Symbol*  symbol  = constant_pool->symbol_at(index);
  1286   // class name?
  1287   if (symbol->byte_at(0) != '(') {
  1288     Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
  1289     SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
  1290     return;
  1293   // then it must be a signature!
  1294   ResourceMark rm(THREAD);
  1295   for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
  1296     if (ss.is_object()) {
  1297       Symbol* class_name = ss.as_symbol(CHECK);
  1298       Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
  1299       SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
  1305 void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {
  1306   EXCEPTION_MARK;
  1307   load_class_by_index(constant_pool, index, THREAD);
  1308   if (HAS_PENDING_EXCEPTION) {
  1309     // Exception happened during classloading. We ignore the exception here, since it
  1310     // is going to be rethrown since the current activation is going to be deoptimized and
  1311     // the interpreter will re-execute the bytecode.
  1312     CLEAR_PENDING_EXCEPTION;
  1313     // Class loading called java code which may have caused a stack
  1314     // overflow. If the exception was thrown right before the return
  1315     // to the runtime the stack is no longer guarded. Reguard the
  1316     // stack otherwise if we return to the uncommon trap blob and the
  1317     // stack bang causes a stack overflow we crash.
  1318     assert(THREAD->is_Java_thread(), "only a java thread can be here");
  1319     JavaThread* thread = (JavaThread*)THREAD;
  1320     bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
  1321     if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
  1322     assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
  1326 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
  1327   HandleMark hm;
  1329   // uncommon_trap() is called at the beginning of the uncommon trap
  1330   // handler. Note this fact before we start generating temporary frames
  1331   // that can confuse an asynchronous stack walker. This counter is
  1332   // decremented at the end of unpack_frames().
  1333   thread->inc_in_deopt_handler();
  1335   // We need to update the map if we have biased locking.
  1336   RegisterMap reg_map(thread, UseBiasedLocking);
  1337   frame stub_frame = thread->last_frame();
  1338   frame fr = stub_frame.sender(&reg_map);
  1339   // Make sure the calling nmethod is not getting deoptimized and removed
  1340   // before we are done with it.
  1341   nmethodLocker nl(fr.pc());
  1343   // Log a message
  1344   Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT,
  1345               trap_request, fr.pc());
  1348     ResourceMark rm;
  1350     // Revoke biases of any monitors in the frame to ensure we can migrate them
  1351     revoke_biases_of_monitors(thread, fr, &reg_map);
  1353     DeoptReason reason = trap_request_reason(trap_request);
  1354     DeoptAction action = trap_request_action(trap_request);
  1355     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
  1357     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
  1358     compiledVFrame* cvf = compiledVFrame::cast(vf);
  1360     nmethod* nm = cvf->code();
  1362     ScopeDesc*      trap_scope  = cvf->scope();
  1363     methodHandle    trap_method = trap_scope->method();
  1364     int             trap_bci    = trap_scope->bci();
  1365     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
  1367     // Record this event in the histogram.
  1368     gather_statistics(reason, action, trap_bc);
  1370     // Ensure that we can record deopt. history:
  1371     // Need MDO to record RTM code generation state.
  1372     bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );
  1374     MethodData* trap_mdo =
  1375       get_method_data(thread, trap_method, create_if_missing);
  1377     // Log a message
  1378     Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",
  1379                               trap_reason_name(reason), trap_action_name(action), fr.pc(),
  1380                               trap_method->name_and_sig_as_C_string(), trap_bci);
  1382     // Print a bunch of diagnostics, if requested.
  1383     if (TraceDeoptimization || LogCompilation) {
  1384       ResourceMark rm;
  1385       ttyLocker ttyl;
  1386       char buf[100];
  1387       if (xtty != NULL) {
  1388         xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
  1389                          os::current_thread_id(),
  1390                          format_trap_request(buf, sizeof(buf), trap_request));
  1391         nm->log_identity(xtty);
  1393       Symbol* class_name = NULL;
  1394       bool unresolved = false;
  1395       if (unloaded_class_index >= 0) {
  1396         constantPoolHandle constants (THREAD, trap_method->constants());
  1397         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
  1398           class_name = constants->klass_name_at(unloaded_class_index);
  1399           unresolved = true;
  1400           if (xtty != NULL)
  1401             xtty->print(" unresolved='1'");
  1402         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
  1403           class_name = constants->symbol_at(unloaded_class_index);
  1405         if (xtty != NULL)
  1406           xtty->name(class_name);
  1408       if (xtty != NULL && trap_mdo != NULL) {
  1409         // Dump the relevant MDO state.
  1410         // This is the deopt count for the current reason, any previous
  1411         // reasons or recompiles seen at this point.
  1412         int dcnt = trap_mdo->trap_count(reason);
  1413         if (dcnt != 0)
  1414           xtty->print(" count='%d'", dcnt);
  1415         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
  1416         int dos = (pdata == NULL)? 0: pdata->trap_state();
  1417         if (dos != 0) {
  1418           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
  1419           if (trap_state_is_recompiled(dos)) {
  1420             int recnt2 = trap_mdo->overflow_recompile_count();
  1421             if (recnt2 != 0)
  1422               xtty->print(" recompiles2='%d'", recnt2);
  1426       if (xtty != NULL) {
  1427         xtty->stamp();
  1428         xtty->end_head();
  1430       if (TraceDeoptimization) {  // make noise on the tty
  1431         tty->print("Uncommon trap occurred in");
  1432         nm->method()->print_short_name(tty);
  1433         tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d",
  1434                    fr.pc(),
  1435                    os::current_thread_id(),
  1436                    trap_reason_name(reason),
  1437                    trap_action_name(action),
  1438                    unloaded_class_index);
  1439         if (class_name != NULL) {
  1440           tty->print(unresolved ? " unresolved class: " : " symbol: ");
  1441           class_name->print_symbol_on(tty);
  1443         tty->cr();
  1445       if (xtty != NULL) {
  1446         // Log the precise location of the trap.
  1447         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
  1448           xtty->begin_elem("jvms bci='%d'", sd->bci());
  1449           xtty->method(sd->method());
  1450           xtty->end_elem();
  1451           if (sd->is_top())  break;
  1453         xtty->tail("uncommon_trap");
  1456     // (End diagnostic printout.)
  1458     // Load class if necessary
  1459     if (unloaded_class_index >= 0) {
  1460       constantPoolHandle constants(THREAD, trap_method->constants());
  1461       load_class_by_index(constants, unloaded_class_index);
  1464     // Flush the nmethod if necessary and desirable.
  1465     //
  1466     // We need to avoid situations where we are re-flushing the nmethod
  1467     // because of a hot deoptimization site.  Repeated flushes at the same
  1468     // point need to be detected by the compiler and avoided.  If the compiler
  1469     // cannot avoid them (or has a bug and "refuses" to avoid them), this
  1470     // module must take measures to avoid an infinite cycle of recompilation
  1471     // and deoptimization.  There are several such measures:
  1472     //
  1473     //   1. If a recompilation is ordered a second time at some site X
  1474     //   and for the same reason R, the action is adjusted to 'reinterpret',
  1475     //   to give the interpreter time to exercise the method more thoroughly.
  1476     //   If this happens, the method's overflow_recompile_count is incremented.
  1477     //
  1478     //   2. If the compiler fails to reduce the deoptimization rate, then
  1479     //   the method's overflow_recompile_count will begin to exceed the set
  1480     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
  1481     //   is adjusted to 'make_not_compilable', and the method is abandoned
  1482     //   to the interpreter.  This is a performance hit for hot methods,
  1483     //   but is better than a disastrous infinite cycle of recompilations.
  1484     //   (Actually, only the method containing the site X is abandoned.)
  1485     //
  1486     //   3. In parallel with the previous measures, if the total number of
  1487     //   recompilations of a method exceeds the much larger set limit
  1488     //   PerMethodRecompilationCutoff, the method is abandoned.
  1489     //   This should only happen if the method is very large and has
  1490     //   many "lukewarm" deoptimizations.  The code which enforces this
  1491     //   limit is elsewhere (class nmethod, class Method).
  1492     //
  1493     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
  1494     // to recompile at each bytecode independently of the per-BCI cutoff.
  1495     //
  1496     // The decision to update code is up to the compiler, and is encoded
  1497     // in the Action_xxx code.  If the compiler requests Action_none
  1498     // no trap state is changed, no compiled code is changed, and the
  1499     // computation suffers along in the interpreter.
  1500     //
  1501     // The other action codes specify various tactics for decompilation
  1502     // and recompilation.  Action_maybe_recompile is the loosest, and
  1503     // allows the compiled code to stay around until enough traps are seen,
  1504     // and until the compiler gets around to recompiling the trapping method.
  1505     //
  1506     // The other actions cause immediate removal of the present code.
  1508     // Traps caused by injected profile shouldn't pollute trap counts.
  1509     bool injected_profile_trap = trap_method->has_injected_profile() &&
  1510                                  (reason == Reason_intrinsic || reason == Reason_unreached);
  1511     bool update_trap_state = !injected_profile_trap;
  1512     bool make_not_entrant = false;
  1513     bool make_not_compilable = false;
  1514     bool reprofile = false;
  1515     switch (action) {
  1516     case Action_none:
  1517       // Keep the old code.
  1518       update_trap_state = false;
  1519       break;
  1520     case Action_maybe_recompile:
  1521       // Do not need to invalidate the present code, but we can
  1522       // initiate another
  1523       // Start compiler without (necessarily) invalidating the nmethod.
  1524       // The system will tolerate the old code, but new code should be
  1525       // generated when possible.
  1526       break;
  1527     case Action_reinterpret:
  1528       // Go back into the interpreter for a while, and then consider
  1529       // recompiling form scratch.
  1530       make_not_entrant = true;
  1531       // Reset invocation counter for outer most method.
  1532       // This will allow the interpreter to exercise the bytecodes
  1533       // for a while before recompiling.
  1534       // By contrast, Action_make_not_entrant is immediate.
  1535       //
  1536       // Note that the compiler will track null_check, null_assert,
  1537       // range_check, and class_check events and log them as if they
  1538       // had been traps taken from compiled code.  This will update
  1539       // the MDO trap history so that the next compilation will
  1540       // properly detect hot trap sites.
  1541       reprofile = true;
  1542       break;
  1543     case Action_make_not_entrant:
  1544       // Request immediate recompilation, and get rid of the old code.
  1545       // Make them not entrant, so next time they are called they get
  1546       // recompiled.  Unloaded classes are loaded now so recompile before next
  1547       // time they are called.  Same for uninitialized.  The interpreter will
  1548       // link the missing class, if any.
  1549       make_not_entrant = true;
  1550       break;
  1551     case Action_make_not_compilable:
  1552       // Give up on compiling this method at all.
  1553       make_not_entrant = true;
  1554       make_not_compilable = true;
  1555       break;
  1556     default:
  1557       ShouldNotReachHere();
  1560     // Setting +ProfileTraps fixes the following, on all platforms:
  1561     // 4852688: ProfileInterpreter is off by default for ia64.  The result is
  1562     // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
  1563     // recompile relies on a MethodData* to record heroic opt failures.
  1565     // Whether the interpreter is producing MDO data or not, we also need
  1566     // to use the MDO to detect hot deoptimization points and control
  1567     // aggressive optimization.
  1568     bool inc_recompile_count = false;
  1569     ProfileData* pdata = NULL;
  1570     if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
  1571       assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");
  1572       uint this_trap_count = 0;
  1573       bool maybe_prior_trap = false;
  1574       bool maybe_prior_recompile = false;
  1575       pdata = query_update_method_data(trap_mdo, trap_bci, reason,
  1576                                    nm->method(),
  1577                                    //outputs:
  1578                                    this_trap_count,
  1579                                    maybe_prior_trap,
  1580                                    maybe_prior_recompile);
  1581       // Because the interpreter also counts null, div0, range, and class
  1582       // checks, these traps from compiled code are double-counted.
  1583       // This is harmless; it just means that the PerXTrapLimit values
  1584       // are in effect a little smaller than they look.
  1586       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
  1587       if (per_bc_reason != Reason_none) {
  1588         // Now take action based on the partially known per-BCI history.
  1589         if (maybe_prior_trap
  1590             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
  1591           // If there are too many traps at this BCI, force a recompile.
  1592           // This will allow the compiler to see the limit overflow, and
  1593           // take corrective action, if possible.  The compiler generally
  1594           // does not use the exact PerBytecodeTrapLimit value, but instead
  1595           // changes its tactics if it sees any traps at all.  This provides
  1596           // a little hysteresis, delaying a recompile until a trap happens
  1597           // several times.
  1598           //
  1599           // Actually, since there is only one bit of counter per BCI,
  1600           // the possible per-BCI counts are {0,1,(per-method count)}.
  1601           // This produces accurate results if in fact there is only
  1602           // one hot trap site, but begins to get fuzzy if there are
  1603           // many sites.  For example, if there are ten sites each
  1604           // trapping two or more times, they each get the blame for
  1605           // all of their traps.
  1606           make_not_entrant = true;
  1609         // Detect repeated recompilation at the same BCI, and enforce a limit.
  1610         if (make_not_entrant && maybe_prior_recompile) {
  1611           // More than one recompile at this point.
  1612           inc_recompile_count = maybe_prior_trap;
  1614       } else {
  1615         // For reasons which are not recorded per-bytecode, we simply
  1616         // force recompiles unconditionally.
  1617         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
  1618         make_not_entrant = true;
  1621       // Go back to the compiler if there are too many traps in this method.
  1622       if (this_trap_count >= per_method_trap_limit(reason)) {
  1623         // If there are too many traps in this method, force a recompile.
  1624         // This will allow the compiler to see the limit overflow, and
  1625         // take corrective action, if possible.
  1626         // (This condition is an unlikely backstop only, because the
  1627         // PerBytecodeTrapLimit is more likely to take effect first,
  1628         // if it is applicable.)
  1629         make_not_entrant = true;
  1632       // Here's more hysteresis:  If there has been a recompile at
  1633       // this trap point already, run the method in the interpreter
  1634       // for a while to exercise it more thoroughly.
  1635       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
  1636         reprofile = true;
  1641     // Take requested actions on the method:
  1643     // Recompile
  1644     if (make_not_entrant) {
  1645       if (!nm->make_not_entrant()) {
  1646         return; // the call did not change nmethod's state
  1649       if (pdata != NULL) {
  1650         // Record the recompilation event, if any.
  1651         int tstate0 = pdata->trap_state();
  1652         int tstate1 = trap_state_set_recompiled(tstate0, true);
  1653         if (tstate1 != tstate0)
  1654           pdata->set_trap_state(tstate1);
  1657 #if INCLUDE_RTM_OPT
  1658       // Restart collecting RTM locking abort statistic if the method
  1659       // is recompiled for a reason other than RTM state change.
  1660       // Assume that in new recompiled code the statistic could be different,
  1661       // for example, due to different inlining.
  1662       if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
  1663           UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {
  1664         trap_mdo->atomic_set_rtm_state(ProfileRTM);
  1666 #endif
  1669     if (inc_recompile_count) {
  1670       trap_mdo->inc_overflow_recompile_count();
  1671       if ((uint)trap_mdo->overflow_recompile_count() >
  1672           (uint)PerBytecodeRecompilationCutoff) {
  1673         // Give up on the method containing the bad BCI.
  1674         if (trap_method() == nm->method()) {
  1675           make_not_compilable = true;
  1676         } else {
  1677           trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
  1678           // But give grace to the enclosing nm->method().
  1683     // Reprofile
  1684     if (reprofile) {
  1685       CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
  1688     // Give up compiling
  1689     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
  1690       assert(make_not_entrant, "consistent");
  1691       nm->method()->set_not_compilable(CompLevel_full_optimization);
  1694   } // Free marked resources
  1697 JRT_END
  1699 MethodData*
  1700 Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
  1701                                 bool create_if_missing) {
  1702   Thread* THREAD = thread;
  1703   MethodData* mdo = m()->method_data();
  1704   if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
  1705     // Build an MDO.  Ignore errors like OutOfMemory;
  1706     // that simply means we won't have an MDO to update.
  1707     Method::build_interpreter_method_data(m, THREAD);
  1708     if (HAS_PENDING_EXCEPTION) {
  1709       assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
  1710       CLEAR_PENDING_EXCEPTION;
  1712     mdo = m()->method_data();
  1714   return mdo;
  1717 ProfileData*
  1718 Deoptimization::query_update_method_data(MethodData* trap_mdo,
  1719                                          int trap_bci,
  1720                                          Deoptimization::DeoptReason reason,
  1721                                          Method* compiled_method,
  1722                                          //outputs:
  1723                                          uint& ret_this_trap_count,
  1724                                          bool& ret_maybe_prior_trap,
  1725                                          bool& ret_maybe_prior_recompile) {
  1726   uint prior_trap_count = trap_mdo->trap_count(reason);
  1727   uint this_trap_count  = trap_mdo->inc_trap_count(reason);
  1729   // If the runtime cannot find a place to store trap history,
  1730   // it is estimated based on the general condition of the method.
  1731   // If the method has ever been recompiled, or has ever incurred
  1732   // a trap with the present reason , then this BCI is assumed
  1733   // (pessimistically) to be the culprit.
  1734   bool maybe_prior_trap      = (prior_trap_count != 0);
  1735   bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
  1736   ProfileData* pdata = NULL;
  1739   // For reasons which are recorded per bytecode, we check per-BCI data.
  1740   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
  1741   if (per_bc_reason != Reason_none) {
  1742     // Find the profile data for this BCI.  If there isn't one,
  1743     // try to allocate one from the MDO's set of spares.
  1744     // This will let us detect a repeated trap at this point.
  1745     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
  1747     if (pdata != NULL) {
  1748       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
  1749         if (LogCompilation && xtty != NULL) {
  1750           ttyLocker ttyl;
  1751           // no more room for speculative traps in this MDO
  1752           xtty->elem("speculative_traps_oom");
  1755       // Query the trap state of this profile datum.
  1756       int tstate0 = pdata->trap_state();
  1757       if (!trap_state_has_reason(tstate0, per_bc_reason))
  1758         maybe_prior_trap = false;
  1759       if (!trap_state_is_recompiled(tstate0))
  1760         maybe_prior_recompile = false;
  1762       // Update the trap state of this profile datum.
  1763       int tstate1 = tstate0;
  1764       // Record the reason.
  1765       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
  1766       // Store the updated state on the MDO, for next time.
  1767       if (tstate1 != tstate0)
  1768         pdata->set_trap_state(tstate1);
  1769     } else {
  1770       if (LogCompilation && xtty != NULL) {
  1771         ttyLocker ttyl;
  1772         // Missing MDP?  Leave a small complaint in the log.
  1773         xtty->elem("missing_mdp bci='%d'", trap_bci);
  1778   // Return results:
  1779   ret_this_trap_count = this_trap_count;
  1780   ret_maybe_prior_trap = maybe_prior_trap;
  1781   ret_maybe_prior_recompile = maybe_prior_recompile;
  1782   return pdata;
  1785 void
  1786 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
  1787   ResourceMark rm;
  1788   // Ignored outputs:
  1789   uint ignore_this_trap_count;
  1790   bool ignore_maybe_prior_trap;
  1791   bool ignore_maybe_prior_recompile;
  1792   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
  1793   query_update_method_data(trap_mdo, trap_bci,
  1794                            (DeoptReason)reason,
  1795                            NULL,
  1796                            ignore_this_trap_count,
  1797                            ignore_maybe_prior_trap,
  1798                            ignore_maybe_prior_recompile);
  1801 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {
  1803   // Still in Java no safepoints
  1805     // This enters VM and may safepoint
  1806     uncommon_trap_inner(thread, trap_request);
  1808   return fetch_unroll_info_helper(thread);
  1811 // Local derived constants.
  1812 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
  1813 const int DS_REASON_MASK   = DataLayout::trap_mask >> 1;
  1814 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
  1816 //---------------------------trap_state_reason---------------------------------
  1817 Deoptimization::DeoptReason
  1818 Deoptimization::trap_state_reason(int trap_state) {
  1819   // This assert provides the link between the width of DataLayout::trap_bits
  1820   // and the encoding of "recorded" reasons.  It ensures there are enough
  1821   // bits to store all needed reasons in the per-BCI MDO profile.
  1822   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  1823   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1824   trap_state -= recompile_bit;
  1825   if (trap_state == DS_REASON_MASK) {
  1826     return Reason_many;
  1827   } else {
  1828     assert((int)Reason_none == 0, "state=0 => Reason_none");
  1829     return (DeoptReason)trap_state;
  1832 //-------------------------trap_state_has_reason-------------------------------
  1833 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  1834   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
  1835   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  1836   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1837   trap_state -= recompile_bit;
  1838   if (trap_state == DS_REASON_MASK) {
  1839     return -1;  // true, unspecifically (bottom of state lattice)
  1840   } else if (trap_state == reason) {
  1841     return 1;   // true, definitely
  1842   } else if (trap_state == 0) {
  1843     return 0;   // false, definitely (top of state lattice)
  1844   } else {
  1845     return 0;   // false, definitely
  1848 //-------------------------trap_state_add_reason-------------------------------
  1849 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
  1850   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
  1851   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1852   trap_state -= recompile_bit;
  1853   if (trap_state == DS_REASON_MASK) {
  1854     return trap_state + recompile_bit;     // already at state lattice bottom
  1855   } else if (trap_state == reason) {
  1856     return trap_state + recompile_bit;     // the condition is already true
  1857   } else if (trap_state == 0) {
  1858     return reason + recompile_bit;          // no condition has yet been true
  1859   } else {
  1860     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
  1863 //-----------------------trap_state_is_recompiled------------------------------
  1864 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  1865   return (trap_state & DS_RECOMPILE_BIT) != 0;
  1867 //-----------------------trap_state_set_recompiled-----------------------------
  1868 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
  1869   if (z)  return trap_state |  DS_RECOMPILE_BIT;
  1870   else    return trap_state & ~DS_RECOMPILE_BIT;
  1872 //---------------------------format_trap_state---------------------------------
  1873 // This is used for debugging and diagnostics, including LogFile output.
  1874 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
  1875                                               int trap_state) {
  1876   DeoptReason reason      = trap_state_reason(trap_state);
  1877   bool        recomp_flag = trap_state_is_recompiled(trap_state);
  1878   // Re-encode the state from its decoded components.
  1879   int decoded_state = 0;
  1880   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
  1881     decoded_state = trap_state_add_reason(decoded_state, reason);
  1882   if (recomp_flag)
  1883     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
  1884   // If the state re-encodes properly, format it symbolically.
  1885   // Because this routine is used for debugging and diagnostics,
  1886   // be robust even if the state is a strange value.
  1887   size_t len;
  1888   if (decoded_state != trap_state) {
  1889     // Random buggy state that doesn't decode??
  1890     len = jio_snprintf(buf, buflen, "#%d", trap_state);
  1891   } else {
  1892     len = jio_snprintf(buf, buflen, "%s%s",
  1893                        trap_reason_name(reason),
  1894                        recomp_flag ? " recompiled" : "");
  1896   return buf;
  1900 //--------------------------------statics--------------------------------------
  1901 Deoptimization::DeoptAction Deoptimization::_unloaded_action
  1902   = Deoptimization::Action_reinterpret;
  1903 const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {
  1904   // Note:  Keep this in sync. with enum DeoptReason.
  1905   "none",
  1906   "null_check",
  1907   "null_assert",
  1908   "range_check",
  1909   "class_check",
  1910   "array_check",
  1911   "intrinsic",
  1912   "bimorphic",
  1913   "unloaded",
  1914   "uninitialized",
  1915   "unreached",
  1916   "unhandled",
  1917   "constraint",
  1918   "div0_check",
  1919   "age",
  1920   "predicate",
  1921   "loop_limit_check",
  1922   "speculate_class_check",
  1923   "rtm_state_change",
  1924   "unstable_if"
  1925 };
  1926 const char* Deoptimization::_trap_action_name[Action_LIMIT] = {
  1927   // Note:  Keep this in sync. with enum DeoptAction.
  1928   "none",
  1929   "maybe_recompile",
  1930   "reinterpret",
  1931   "make_not_entrant",
  1932   "make_not_compilable"
  1933 };
  1935 const char* Deoptimization::trap_reason_name(int reason) {
  1936   if (reason == Reason_many)  return "many";
  1937   if ((uint)reason < Reason_LIMIT)
  1938     return _trap_reason_name[reason];
  1939   static char buf[20];
  1940   sprintf(buf, "reason%d", reason);
  1941   return buf;
  1943 const char* Deoptimization::trap_action_name(int action) {
  1944   if ((uint)action < Action_LIMIT)
  1945     return _trap_action_name[action];
  1946   static char buf[20];
  1947   sprintf(buf, "action%d", action);
  1948   return buf;
  1951 // This is used for debugging and diagnostics, including LogFile output.
  1952 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
  1953                                                 int trap_request) {
  1954   jint unloaded_class_index = trap_request_index(trap_request);
  1955   const char* reason = trap_reason_name(trap_request_reason(trap_request));
  1956   const char* action = trap_action_name(trap_request_action(trap_request));
  1957   size_t len;
  1958   if (unloaded_class_index < 0) {
  1959     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",
  1960                        reason, action);
  1961   } else {
  1962     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
  1963                        reason, action, unloaded_class_index);
  1965   return buf;
  1968 juint Deoptimization::_deoptimization_hist
  1969         [Deoptimization::Reason_LIMIT]
  1970     [1 + Deoptimization::Action_LIMIT]
  1971         [Deoptimization::BC_CASE_LIMIT]
  1972   = {0};
  1974 enum {
  1975   LSB_BITS = 8,
  1976   LSB_MASK = right_n_bits(LSB_BITS)
  1977 };
  1979 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
  1980                                        Bytecodes::Code bc) {
  1981   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  1982   assert(action >= 0 && action < Action_LIMIT, "oob");
  1983   _deoptimization_hist[Reason_none][0][0] += 1;  // total
  1984   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
  1985   juint* cases = _deoptimization_hist[reason][1+action];
  1986   juint* bc_counter_addr = NULL;
  1987   juint  bc_counter      = 0;
  1988   // Look for an unused counter, or an exact match to this BC.
  1989   if (bc != Bytecodes::_illegal) {
  1990     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
  1991       juint* counter_addr = &cases[bc_case];
  1992       juint  counter = *counter_addr;
  1993       if ((counter == 0 && bc_counter_addr == NULL)
  1994           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
  1995         // this counter is either free or is already devoted to this BC
  1996         bc_counter_addr = counter_addr;
  1997         bc_counter = counter | bc;
  2001   if (bc_counter_addr == NULL) {
  2002     // Overflow, or no given bytecode.
  2003     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
  2004     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
  2006   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
  2009 jint Deoptimization::total_deoptimization_count() {
  2010   return _deoptimization_hist[Reason_none][0][0];
  2013 jint Deoptimization::deoptimization_count(DeoptReason reason) {
  2014   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  2015   return _deoptimization_hist[reason][0][0];
  2018 void Deoptimization::print_statistics() {
  2019   juint total = total_deoptimization_count();
  2020   juint account = total;
  2021   if (total != 0) {
  2022     ttyLocker ttyl;
  2023     if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
  2024     tty->print_cr("Deoptimization traps recorded:");
  2025     #define PRINT_STAT_LINE(name, r) \
  2026       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
  2027     PRINT_STAT_LINE("total", total);
  2028     // For each non-zero entry in the histogram, print the reason,
  2029     // the action, and (if specifically known) the type of bytecode.
  2030     for (int reason = 0; reason < Reason_LIMIT; reason++) {
  2031       for (int action = 0; action < Action_LIMIT; action++) {
  2032         juint* cases = _deoptimization_hist[reason][1+action];
  2033         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
  2034           juint counter = cases[bc_case];
  2035           if (counter != 0) {
  2036             char name[1*K];
  2037             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
  2038             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
  2039               bc = Bytecodes::_illegal;
  2040             sprintf(name, "%s/%s/%s",
  2041                     trap_reason_name(reason),
  2042                     trap_action_name(action),
  2043                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
  2044             juint r = counter >> LSB_BITS;
  2045             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
  2046             account -= r;
  2051     if (account != 0) {
  2052       PRINT_STAT_LINE("unaccounted", account);
  2054     #undef PRINT_STAT_LINE
  2055     if (xtty != NULL)  xtty->tail("statistics");
  2058 #else // COMPILER2 || SHARK
  2061 // Stubs for C1 only system.
  2062 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  2063   return false;
  2066 const char* Deoptimization::trap_reason_name(int reason) {
  2067   return "unknown";
  2070 void Deoptimization::print_statistics() {
  2071   // no output
  2074 void
  2075 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
  2076   // no udpate
  2079 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  2080   return 0;
  2083 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
  2084                                        Bytecodes::Code bc) {
  2085   // no update
  2088 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
  2089                                               int trap_state) {
  2090   jio_snprintf(buf, buflen, "#%d", trap_state);
  2091   return buf;
  2094 #endif // COMPILER2 || SHARK

mercurial