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